diff --git a/skills/make-custom-apps/examples/current-knowledge/README.md b/skills/make-custom-apps/examples/current-knowledge/README.md index 4b44efc..08a2816 100644 --- a/skills/make-custom-apps/examples/current-knowledge/README.md +++ b/skills/make-custom-apps/examples/current-knowledge/README.md @@ -28,7 +28,7 @@ Strength words in the catalog follow the same split: `must` only for documented | Guide | Teaches | Main authority | |---|---|---| -| [dates-helpers](guides/dates-helpers.md) | Parsing provider date-times, polling order, tracing helper functions | Parsing is required where the provider format is not auto-parsed, with temporal exceptions (date-only, time-only, unknown zone, non-timestamp numbers); canonical ISO text is a documented ambiguity (recommendation to convert, not a blanket must-parse); order is a documented recommendation | +| [dates-helpers](guides/dates-helpers.md) | Parsing provider date-times, polling order, tracing helper functions | Parsing is required where the provider format is not auto-parsed, with temporal exceptions (date-only, time-only, unknown zone, non-timestamp numbers); output date-times are parsed even when already ISO (documented recommendation, Required in marketplace review); order is a documented recommendation | | [selectors-mode](guides/selectors-mode.md) | RPC-backed selects, `mode: "edit"`, nested selects, options vs. field schemas, `option.description` | Documented requirement for mappable Get/Update/Delete identifiers; hierarchy-based recommendations elsewhere; per-option `description` is inferred UX guidance (not found on the inspected public Select or mappable-parameters pages), verified by read-back | | [rpc-page-budgets](guides/rpc-page-budgets.md) | Page size, request budget, record limit and `pagination.page` | Hard ceilings and role-specific requirements (options output limit above 500 items, sample `limit: 1`); recommendations otherwise; the fixed-literal limit is a fixture convention | | [headers-merge](guides/headers-merge.md) | Base headers, module headers, the `{{...}}` collection spread | Documented behaviour | diff --git a/skills/make-custom-apps/examples/current-knowledge/catalog.json b/skills/make-custom-apps/examples/current-knowledge/catalog.json index 891ab45..a29b1dd 100644 --- a/skills/make-custom-apps/examples/current-knowledge/catalog.json +++ b/skills/make-custom-apps/examples/current-knowledge/catalog.json @@ -66,7 +66,7 @@ { "id": "dates-helpers", "title": "Dates and app helpers", - "summary": "Polling triggers need an order that matches the provider request and, where the provider format is not auto-parsed, a date that Make can actually parse (temporal exceptions apply; canonical ISO text is a documented ambiguity, not a blanket must-parse); helper functions must be defined, reachable and genuinely transform their input.", + "summary": "Polling triggers need an order that matches the provider request and, where the provider format is not auto-parsed, a date that Make can actually parse (temporal exceptions apply; a documented ISO cursor value maps directly, while output date-times are parsed even when ISO); helper functions must be defined, reachable and genuinely transform their input.", "guide": "guides/dates-helpers.md", "sources": ["doc-trigger", "doc-iml", "doc-epoch", "doc-input-processing", "doc-iml-tests", "doc-bp-mappable-parameters", "research-generic-complete-app"], "recipes": ["dates-helper-trace"] @@ -245,7 +245,7 @@ "rules": ["CK-DATE-ORDER", "CK-DATE-PARSE", "CK-HELPER-TRACE"], "applicability": { "appliesWhen": ["A polling trigger uses type date with a provider timestamp.", "A module output calls an app helper on a provider field."], - "notWhen": ["The trigger uses type id and no date field.", "The provider already returns ISO 8601 with an explicit offset or UTC marker."], + "notWhen": ["The trigger uses type id and no date field.", "The trigger date is already ISO 8601 with an explicit offset or UTC marker (cursor only; output date-times are still parsed)."], "exceptions": [ { "condition": "The provider value is date-only or time-only.", "effect": "Do not append a zone or time; a helper must preserve such values unchanged, and the trigger needs a provider-specific decision." }, { "condition": "The provider timestamp carries no timezone.", "effect": "Treating it as UTC is an assumption to record, not a fact; confirm the provider's zone before relying on ordering." }, diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/auth-context.md b/skills/make-custom-apps/examples/current-knowledge/guides/auth-context.md index 73df211..6adf0e1 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/auth-context.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/auth-context.md @@ -82,6 +82,69 @@ The checker's `CK-SECRET-LOG` rule applies this to fixtures: a Base authorisatio } ``` +### One list per block, built from where that block puts the secret + +**Documented behaviour (sanitization page).** A request without `log.sanitize` writes no request or response log, so nobody can debug it, and the list is still required. A request with a list is logged, and only the paths in the list are masked. **Not stated on the public pages (confirm in a test run's log):** an empty list (`"sanitize": []`) counts as a list. It turns logging on and masks nothing. + +So a missing list hides the log, while a list that misses the secret shows the secret in clear text. A check that only asks whether a block has a list catches none of these common causes: + +* **A list copied from another block.** The token block sends the credentials in the body. The refresh block sends the refresh token as `Authorization: Bearer`, but its list still names the token block's body paths. The same mistake shows up when an `invalidate` posts the token in the body but its list masks only the header. It also shows up when a connection check sends the token in a custom header (for example `x-session-token`) but its list names only `request.headers.authorization`. +* **The right key in the wrong section.** `request.body.client_secret` does not mask a client secret sent in `qs`. That needs `request.qs.client_secret`. +* **IML quoting in a path.** A sanitize path is not an IML expression. A hyphenated header name is one plain segment: `request.headers.x-api-key`. Backticks (`` request.headers.`x-api-key` ``) become part of the name. The path then matches nothing, and the key stays in clear text with no error. + +Go through each block: `preauthorize`, `token`, `refresh`, `info`, `invalidate`, the check of a basic connection, Base, and every module or RPC that places a credential where Base does not mask it. For each one, list what the block sends (headers, query, body) and what it receives (response headers, response body). Then write that block's list from this inventory. Use an empty list only when no logged field carries a secret. + +```json +{ + "refresh": { + "url": "https://auth.example.com/refresh", + "method": "POST", + "headers": { "authorization": "Bearer {{data.refreshToken}}" }, + "response": { "data": { "accessToken": "{{body.accessToken}}", "refreshToken": "{{body.refreshToken}}" } }, + "log": { "sanitize": ["request.headers.authorization", "response.body.accessToken", "response.body.refreshToken"] } + } +} +``` + +### Secrets inside a text, XML or raw body + +**Documented behaviour (authorization and sanitization best practice).** A field path such as `request.body.client_secret` addresses a key of a parsed body (JSON or urlencoded). Some bodies are sent as one string, and a string has no keys. This covers `type` `text` (or `string` or `raw`), an XML or SOAP envelope, and a string returned by a custom function. Neither a field path nor a Base header path reaches a secret written into such a string. Mask the secret by its value instead: `request.body` replaces every occurrence of that value in the logged body with `***`. The rest of the body stays readable for debugging. + +**Not stated on the public pages; confirm in a test run's log.** The name inside `<>` is looked up in the context where the request runs, so the [table above](#where-each-variable-lives) applies. Name the variable the request reads the secret from. In a connection block that is, for example, `parameters.*`, `data.*` or `common.*`. In a module or RPC it is usually `connection.*`; a secret the module takes as an input is `parameters.*`, as in the documented example, and app common data is `common.*`. The value is matched exactly as stored, so an encoded copy (base64, XML-escaped) is not found. If the name resolves to nothing, the whole field is masked. `request.body` with no field and no value also masks the whole body. That is safe, but it hides the request you need for debugging. + +A response declared or detected as XML is parsed before it is logged, so a field path can reach a secret in it. Below the root element every element is parsed as an array. A path that passes through such an element needs an array step on it, and array steps work only for all-lower-case names (see the next section). The last element can be named without brackets, which masks its whole array. + +```json +{ + "url": "/service", + "method": "POST", + "type": "text", + "headers": { "content-type": "text/xml" }, + "body": "{{buildEnvelope(parameters, connection)}}", + "log": { "sanitize": ["request.body", "request.body"] } +} +``` + +### Arrays, and the limits of path matching + +**Not described in the public request reference; confirm each mask in a test run's log.** A path step can address array elements: + +* `items[*]` covers every element: `response.body.data[*].access_token` masks the token in each object of a returned list. Nested arrays need one `[*]` per level. A payload that can nest to different depths needs one entry per depth the provider can return. +* `items[1]` covers only the first element, because counting starts at 1. `items[]` and `items[0]` match nothing, and no error is shown. +* An array step only finds an array whose key is all lower-case in the payload. For a key such as `lineItems`, or an XML element such as `SessionId`, name the array without brackets (`response.body.lineItems`). This masks the whole array: a coarser mask, but the secret is hidden. +* This narrows the case-insensitivity note under Pitfalls. Only the field and header names after the section name are case-insensitive. The `request.`/`response.` prefix and the section name (`qs`, `headers`, `body`) must be lower-case. `request.headers.Authorization` works. `Request.Headers.authorization` and `request.Headers.authorization` are skipped without an error. + +A listed path is masked whether or not it holds a secret. Listing a bulky non-secret field, such as base64 file content or a raw message, is a legitimate way to keep the log readable. Do not report such an entry as a defect or remove it as noise. Binary `buffer` values need no entry: the log already shows them as a short placeholder with length and checksum. + +```json +"log": { "sanitize": [ + "request.headers.authorization", + "response.body.data[*].access_token", + "response.body.files[*].content", + "response.body.files[*].versions[*].content" +] } +``` + ## Rationale Credentials are the one thing a log must never contain. Because the connection block, Base and modules each see a different slice of variables, the safe habit is to keep credentials in Base from `{{connection.*}}`, keep token handling in the connection, and sanitise every path where a secret passes. @@ -96,6 +159,12 @@ Credentials are the one thing a log must never contain. Because the connection b * Sanitising only the request while the secret also appears in the response, or naming a path that is not where the secret actually sits. Sanitize paths are written in dot notation and are **case-insensitive** (documented in the request reference), so `request.headers.Authorization` and `request.headers.authorization` match the same path. Casing alone is never a sanitisation defect; the lower-case spelling used in the examples is only a consistency convention. * Forgetting the response side: the access token appears in the token response. * Using `token.condition` with an authorisation-code flow. +* Copying one block's `log.sanitize` list into another block, or Base's list into a connection block, without checking where that block puts the secret: a refresh token in a header, a token in an `invalidate` body, a credential in `qs` or in a custom header. +* Reading an empty `log.sanitize` list as "no logging". It turns logging on and masks nothing. +* Writing a sanitize path like an IML expression or a JavaScript index: backticks around a header name, `[]`, or the 0-based `[0]`. None of them is path syntax, and each matches nothing without an error. Use the plain name and `[*]` (or the 1-based `[1]`). +* Exception to the case-insensitivity pitfall for sanitize paths: the `request.`/`response.` prefix and the section name (`qs`, `headers`, `body`) must be lower-case. `Request.Headers.authorization` is skipped without an error and leaves the header in clear text. +* Masking a secret inside a text, XML or raw body with a field path, which cannot reach into a string. Use the value form, for example `request.body` in a module. +* Removing a sanitize entry for a bulky, non-secret field as noise. ## Exceptions and applicability @@ -108,6 +177,17 @@ Credentials are the one thing a log must never contain. Because the connection b * `log.sanitize` mandatory and its case-insensitive dot-notation paths: **documented requirement**. The variable roles of `parameters`, `common` and `data` in connection communication: **documented** (variable table and code-grant example). The `data`/`parameters`/`connection` equivalence in connection communication: **runtime-confirmed, adjudicated allowance**, not read from the public variable table (which describes variable roles only); `common` is outside that equivalence. * Which header names count as sensitive and which body keys are secret-named: **inferred implementation pattern** (a regular expression in the checker). Any real secret path outside those patterns still needs your own review. * The checker is static; it does not call an authorisation server. +* No request or response log without a sanitize list, and the value form `request.body` for a string body: **documented behaviour** (sanitization page; authorization and sanitization best practice). The following are not stated by the public request reference; treat them as expectations to confirm in a run's log: + * an empty list turns logging on and masks nothing; + * a hyphenated header name is one plain segment, and backticks become part of the name; + * `[*]` and the 1-based `[n]` array steps work, while `[]` and `[0]` match nothing; + * array steps need an all-lower-case key; + * the prefix and section name must be lower-case, while field and header names are case-insensitive; + * the name in `<>` is looked up in the request's own context, its value is matched exactly as stored, and a name that resolves to nothing masks the whole field; + * XML responses are parsed, with every element below the root as an array, before they are logged; + * binary buffers are logged as a placeholder with length and checksum. + + Confirm each mask in the sanitized log of a real run. A static reading cannot show that a path matched. ## Fixtures diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/connections-and-oauth.md b/skills/make-custom-apps/examples/current-knowledge/guides/connections-and-oauth.md index 3aa2495..0843937 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/connections-and-oauth.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/connections-and-oauth.md @@ -15,6 +15,14 @@ Basic, JWT, OAuth 1.0 and OAuth 2.0 each have their own communication blocks and Editable connections and connection metadata are documented separately; changing what a user can edit on a connection is a design decision with compatibility consequences for existing connections. +### Connection label (metadata) + +See [base and connections](../../../references/base-and-connections.md#bind-the-connection-label-to-a-returned-field) — the label's documented shape and 512-character limit, a field the check really returns, non-secret identity fields, and fallbacks for missing parts. + +### Private keys, certificates and signed assertions + +When the provider authenticates with key material, collect it with the parameter types built for it: `pkey` for a PEM private key and `cert` for a PEM certificate. Both accept a pasted PEM or extract it from a P12 or PFX file. Never collect a private key in a `text` parameter, which shows it in clear. Some grants have the connection sign its own assertion, such as a JWT bearer grant or a client assertion. Sign it with the documented `jwt` function and the algorithm the provider requires; for an RSA key, that is `RS256` with the `pkey` value as the key. The documentation lists `HS256`, `HS384`, `HS512` and `RS256` as the supported algorithms. Give the assertion the validity and unique identifier the provider requires, for example a few minutes and a fresh `jti`. While it is valid, a signed assertion works as a bearer credential. Add its request path (for example `request.body.assertion` or `request.body.client_assertion`) to `log.sanitize`, together with the client secret and the returned tokens. + ## Trace the whole lifecycle 1. **Authorise.** Collect client credentials and user consent; keep client credentials (app-level) separate from user tokens. @@ -29,10 +37,30 @@ Editable connections and connection metadata are documented separately; changing Providers differ. A refresh response can omit the refresh token (keep the stored one), rotate it (replace the stored one, or later refreshes fail), omit the expiry, or omit optional fields. Decide each case from the provider contract and the documented persistence model. A missing assignment in the refresh response is not, by itself, proof of token loss; the question is whether the provider rotates. Automatic re-execution on a failed call is suitable only for a grant that can be repeated without new user interaction; never replay a one-use authorisation code. +**Lifetimes the response does not state.** When the token response has no `expires_in` but the provider documents the access-token lifetime, store that lifetime minus a safety margin in `response.data.expires`, so the renewal condition still has a date to compare. For a documented one-hour token, the OAuth 2.0 page uses `"expires": "{{addMinutes(now, 55)}}"`. When there is no `refresh_expires_in` but the documentation says how long a refresh token lives, set `response.expires` from that documented value rather than a guess, for example `"{{addYears(now, 1)}}"` for one year. A refresh token that does not expire needs no `response.expires`. A guessed lifetime that is too long lets modules start with an expired access token. It can also let the refresh token stop working before Make asks the user to reauthorise. + +**Restating the grant expiry on refresh.** A `response.expires` in the `refresh` block sets the reauthorisation date again on every refresh. That is right only when a refresh starts a new refresh-token lifetime: either the refresh response returns a new refresh token with its own `refresh_expires_in`, or the provider documents a sliding lifetime. Some providers document a lifetime that counts from the original consent. There, a refresh block that writes `{{addDays(now, 90)}}` keeps moving the date forward. The provider then rejects the refresh token while Make still treats the grant as valid, and users see refresh errors instead of a reauthorisation prompt. In that case, store the original date in `response.data` when the token is first issued and write it back on refresh, for example `"expires": "{{ifempty(data.grantExpires, addDays(now, 90))}}"`. The provider's documentation decides which model applies. + +### Asking for a refresh token + +A `refresh` block only helps if the authorisation returned a refresh token in the first place. Many providers issue one only when the authorise request asks for offline access. They ask for it either with a query parameter or with a dedicated scope, such as the OpenID Connect `offline_access` scope, which the documented code-grant example puts in the default scope. Some issue a new refresh token on a repeated consent only when the consent screen is forced (in OpenID Connect, `prompt=consent`). Without these parameters, the first connection can work while a reauthorisation, or a second connection to the same account, comes back without a refresh token. The connection then stops working when that access token expires. Parameter names differ by provider, so send exactly what the provider documents. Forcing consent shows the consent screen on every authorisation, so add it only when the provider needs it to issue the token again. Pair it with a refresh response that keeps the stored refresh token when the provider omits it (see Pitfalls). + +### Choosing the check request + +See [base and connections](../../../references/base-and-connections.md#a-check-that-every-module-capable-credential-passes) — choosing a check that every credential the modules can use passes, including least-privilege keys. + +### Rejecting credentials the app cannot use + +Make saves a connection whenever its check request does not fail, and an HTTP status of 400 or higher fails on its own. A provider that answers 200 for an invalid credential needs `response.valid` built from its documented error flag ([requests-and-responses](../../../references/requests-and-responses.md)). The same check can reject a credential that the provider accepts but this connection's modules cannot use, for example a key of another type that the app serves with a separate connection: `"valid": {"condition": "{{body.data.me.kind == 'member'}}", "message": "This key type is not supported by this connection. Use the other connection type."}`. Base the condition on identity data that the check already returns and the provider documents. `message` is the error shown when the condition is false, so it should tell the user what to do. Never put a success text such as "Connected as …" there. The wrong credential then fails once, when the connection is created, instead of failing in every module. + ## Additional OAuth scopes Scopes must cover the operations the app promises. An extra-scopes input is a **conditional** capability: it matters for universal modules that can reach endpoint groups outside the baseline grant, where the guidance is a user-supplied extension merged with the normal scopes, plus an explanation of whether the user edits or recreates the connection to change the grant. It is not mandatory for every OAuth connection; a fixed set of operations covered by one baseline scope needs none. A parameter name or separator seen in one example is not a cross-provider rule. See [universal-modules-and-scopes](universal-modules-and-scopes.md). +When the extension is warranted, the documented pattern builds the authorise `scope` from Make's list plus the optional array parameter: `{{join(distinct(merge(oauth.scope, ifempty(parameters.additionalScopes, emptyarray))), ' ')}}`. The parameter name is the app's choice; the pages use `additionalScopes` and `scopes`. `ifempty(..., emptyarray)` keeps `merge` working when the user leaves the optional array empty. `distinct` stops a scope from being sent twice when the user repeats it or it is already requested. The `join` separator is the provider's; the documentation shows both a space and a comma. The parameter's help says that the scopes are for the universal module and that the user must add scopes for every call they plan to make. The universal module can show the documented `banner` that tells the user to edit or recreate the connection. + +Declare each module's own scope on the module, including the scopes its RPCs need. Make asks the user to extend permissions when a module needs a scope the connection does not have yet. A new app can then keep the connection's default scope to what every connection needs, so users grant only what the modules they use require. In an existing app, changing the default scope or module scopes is an authentication migration, not an incidental edit ([maintenance](../../../references/maintenance.md)). + ## Dependent components share one connection Modules, RPCs, webhooks and their attach/detach RPCs each list the connections they accept. Every RPC a module uses must match the module's connection list, including an RPC that makes no request. A shared webhook additionally needs the connection relationship that routes events to the right account (`uid` in `info` and in the webhook). @@ -50,7 +78,10 @@ Authentication fails far from where it is configured: a token that cannot refres * Making an extra-scopes field mandatory for a connection whose operations never need it, or declaring a universal call broken without checking its endpoint group's required scopes. * Declaring an inconsistency because one block uses `data.x` and another `parameters.x` inside connection communication. * Treating `common` as the same store as `data`/`parameters`, which defeats the documented `ifempty(parameters.clientId, common.clientId)` fallback. +* Reading a redacted placeholder (for example `` or `***`) in supplied common data or connection data as missing configuration. It is present-but-hidden configuration: the value exists in the real app and was masked for review, so do not report it missing or replace it, and never write the placeholder back as a value in an adjusted file (a returned `` would overwrite the real secret). * Credentials placed per module (query string, body or header) instead of once in Base, which is a maintainability and sanitization risk only; a placement the provider API accepts is not a defect, and one it does not accept is a functional fix. +* A renewal condition that reads a value no block stores. For example, `{{data.expires < addMinutes(now, 1)}}` while neither the `token` response nor the `refresh` response, where there is one, writes `response.data.expires`: they write only the access token, or put the access-token lifetime in `response.expires`. With no stored expiration the documented condition is true, so Make requests a token or a refresh before every module use. That is one extra request per call, and none of the caching the condition was written for. Check every key a `condition` reads against what the `token` and `refresh` responses write to `response.data`. +* `token` and `refresh` responses that store the same value under different keys or in different types. For example, the first token is stored as `token` while refresh writes `accessToken`. Or `expires` is an epoch number (`formatDate(now, 'X')` plus seconds) in one block and a date (`addSeconds(now, body.expires_in)`) in the other. Base reads one key: if it reads the refresh key, the first token is unreachable until the first refresh; if it reads the token key, every refreshed token is ignored. A condition that compares a number with `addMinutes(now, 1)` does not measure time. Write every key that Base, modules or conditions read with the same name and type in both blocks, as the documented code-grant example does. ## Exceptions and applicability @@ -63,6 +94,7 @@ Authentication fails far from where it is configured: a token that cannot refres * Block names, expiry directives, `token.condition` restrictions and the shared-webhook `uid` requirement: **documented behaviour / requirement** (OAuth 2.0 and connection pages). * Token response handling, rotation and check design: **provider-dependent**, with an **inferred implementation pattern** for the verification steps. * No static check here executes an authorisation server; real authorisation, refresh and invalid-credential runs are the only proof. +* Documented lifetime fallbacks, the additional-scopes expression, module scopes and the extend-permissions dialog, `response.valid` with `condition`/`message` in the check, the metadata shape and 512-character limit, the `pkey`/`cert` parameter types and the algorithms of `jwt`: **documented behaviour / requirement**. Offline-access and consent parameters (standardised by OpenID Connect, named by each provider), sliding or fixed refresh-token lifetimes, assertion validity and per-permission keys: **provider-dependent**. The effect of a condition that reads an unstored key, and of keys or types that differ between `token` and `refresh`: **inferred implementation pattern** from the documented condition semantics and the code-grant example. ## Sources @@ -78,3 +110,8 @@ Authentication fails far from where it is configured: a token that cannot refres * https://developers.make.com/custom-apps-documentation/best-practices/connections/additional-oauth-scopes * https://developers.make.com/custom-apps-documentation/best-practices/base/authorization-and-sanitization * https://spec.openapis.org/oas/v3.0.3.html#security-scheme-object +* https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/valid +* https://developers.make.com/custom-apps-documentation/component-blocks/scope +* https://developers.make.com/custom-apps-documentation/block-elements/parameters/pkey +* https://developers.make.com/custom-apps-documentation/block-elements/parameters/cert +* OpenID Connect Core 1.0, section 11, Offline Access (the `offline_access` scope and `prompt=consent`; not a Make source) diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/dates-helpers.md b/skills/make-custom-apps/examples/current-knowledge/guides/dates-helpers.md index 736af28..08192cd 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/dates-helpers.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/dates-helpers.md @@ -10,13 +10,20 @@ Dates are a place where polling triggers and search modules can go quietly wrong **Documented recommendation.** Output date-times should be parsed so that the user gets a real date, for example `{{parseDate(item.createdAt, 'X')}}`. The public output-processing page lists the exceptions: values that are only a time, only a date, or a date and time without a timezone (unless the provider documents UTC or another fixed zone), and numeric timestamps (parse only if the provider clearly documents the field as one; never assume a long number is a timestamp). The page also says: do not substitute the Make user's or organisation's timezone for a zone the provider has not documented. -**Documented requirement.** Output date-times use Make's ISO representation, and the interface declares them as `date`; a nonconforming (non-ISO) format needs conversion. +**Documented requirement.** Output date-times use Make's ISO representation, and the interface declares them as `date`; a nonconforming (non-ISO) format needs conversion, and ISO text is parsed too (below). -**Documented recommendation, with a source ambiguity.** For each emitted datetime, trace the value's type and conversion, then check the matching `date` interface. HTTP JSON parsing leaves an ISO value as text, and the interface is not proof of conversion. The focused output-processing page recommends a parsed datetime path, so prefer parsing raw text or tracing an equivalent Date-producing conversion, subject to the exceptions above. If the traced value is already Date-valued, preserve it; do not demand a second parse. The absence of `parseDate` alone proves neither a defect nor a runtime failure. The general polling example also passes an ISO field directly into output with a `date` interface, so explicit parsing of canonical raw ISO text is an authoring recommendation, not an unambiguous platform violation, automatic blocker or proof of runtime failure. Record that source ambiguity before assigning a conversion finding. A missing `date` interface declaration is a separate declaration concern. Polling `trigger.date` is a separate path (below). +**Documented recommendation, required in marketplace review.** For each emitted datetime, trace the value's type and conversion, then check the matching `date` interface. HTTP JSON parsing leaves an ISO value as text, and the interface is not proof of conversion. The focused output-processing page recommends a parsed datetime path, so parse raw text with the provider's format, even when it is already ISO, or trace an equivalent Date-producing conversion, such as the app's own IML function that parses the field, subject to the exceptions above. If the traced value is already Date-valued, preserve it; do not demand a second parse. The absence of the `parseDate` token is not the test; unparsed text is, and it is not a runtime failure. The general polling example also passes an ISO field directly into output with a `date` interface, but that example is no exemption: marketplace review treats an unparsed output date-time as Required. A missing `date` interface declaration is a separate declaration concern. Polling `trigger.date` is a separate path (below). -**Documented recommendation.** For date-only values, keep the provider's format and declare the interface field as `type: text`. Preserve the provider response (`output: "{{item}}"`, `output: "{{body}}"`) and do not rename or reshape fields without reason. This composes with conversion: keep every unrelated field and transform only the applicable temporal fields. Do not teach that a helper must change an already conforming value; an identity result is a defect only where conversion was actually needed. +**Documented recommendation.** For date-only values, keep the provider's format and declare the interface field as `type: text`. Preserve the provider response (`output: "{{item}}"`, `output: "{{body}}"`) and do not rename or reshape fields without reason. This composes with conversion: keep every unrelated field and transform only the applicable temporal fields. Do not teach that a helper must change a value that is already a Date or that an exception keeps as text; an identity result is a defect only where conversion was actually needed. -**Review each emitted temporal field in this order:** establish meaning, zone and unit; inspect its output expression or helper and the matching interface declaration; apply the documented exception. The bare absence of the token `parseDate` does not prove failure: inspect equivalent conversion and the resulting representation. Applicable omissions are authoring corrections, not invented observed outages. A raw field that is retained but not declared in the interface is a declaration gap, not proof it was dropped or cannot be mapped (Make can suggest undeclared incoming fields); an explicit projection that discards a required field is a different, demonstrable loss. Worked example: [role-application-examples](role-application-examples.md). +**Review each emitted temporal field in this order:** establish meaning, zone and unit; inspect its output expression or helper and the matching interface declaration; apply the documented exception, and report an undocumented zone as uncertain rather than dismissing it. The bare absence of the token `parseDate` is not the test: inspect equivalent conversion and the resulting representation; ISO text that reaches the output unparsed is a finding. Applicable omissions are required corrections, not invented observed outages. A raw field that is retained but not declared in the interface is a declaration gap, not proof it was dropped or cannot be mapped (Make can suggest undeclared incoming fields); an explicit projection that discards a required field is a different, demonstrable loss. Worked example: [role-application-examples](role-application-examples.md). + +### A date parameter sent as a calendar date or as parts + +**Documented behaviour.** The date parameter page's own example: 17 September 2025 entered in Prague with `time: false` reaches the request as `2025-09-16T22:00:00.000Z`. Where a module uses a `date` parameter for a value the provider wants as a calendar date, or as day, month and year, derive them with `formatDate` in the communication. Without a zone argument it formats in the organisation's timezone, so `{{formatDate(parameters.startDate, 'YYYY-MM-DD')}}` returns `2025-09-17` when that is the zone the user entered the date in. The first ten characters of the ISO text return `2025-09-16`. JavaScript date methods in a helper read the instant in whatever zone runs the function, so they can return the 16th too: the previous day for users east of UTC. Inside a helper, call `iml.formatDate` instead. For a value that is only a date, a `text` parameter whose help states the format is still the documented alternative (Input side under [Choosing the temporal meaning first](#choosing-the-temporal-meaning-first)). + +* **Numeric parts.** `parseNumber(formatDate(parameters.endDate, 'DD'))`, and the same with `MM` and `YYYY`. An object assembled from those parts in `temp` still exists when the date is empty, so emit it only when the date is set: `"endDate": "{{if(parameters.endDate, temp.endDate, undefined)}}"`. The object is derived, so omitting it drops nothing the user set. +* **Help text that names another format.** A `date` parameter whose help says `YYYY-MM-DD` while the request maps it unchanged tells the user one format and sends another (the ISO date-time above). Format it as shown, or use a `text` parameter whose help states the format. ## Polling trigger order @@ -48,6 +55,35 @@ A helper is only useful if the field travels through it and it changes the value The recipe's `functions/normalizeDate.js` is the teaching helper. The checker's `CK-HELPER-TRACE` rule performs a textual version of those three steps and rejects an undefined helper, a helper that ignores its argument, an identity helper and a call that is not given a provider field. "Given a provider field" means a real `item.FIELD` reference outside quoted literals in some argument: `normalizeDate('item.updated_at')` passes a constant string, not the field, while `normalizeDate(item.updated_at, 'YYYY-MM-DD')` passes the field plus a format literal. This is lexical provenance only; it does not execute the helper or show the conversion is correct. +### Helpers that decide by value shape + +**Inferred implementation pattern.** A helper that walks a whole response and converts every value that *looks* like a timestamp can pass all three links above and still convert the wrong values, because it decides per value instead of per documented field. Read what its pattern accepts and what it rejects: + +* **Zone-less values.** A pattern that does not require `Z` or an offset (`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}`, or one that also accepts `YYYY-MM-DD HH:mm:ss`) hands values such as `2026-10-29T13:45:30` to `iml.parseDate`. Without a zone argument, `parseDate` reads them in the organisation's timezone. That is the substitution the output-processing page rules out unless the provider documents a zone ([Exceptions and applicability](#exceptions-and-applicability)). +* **Prefix matches.** A pattern anchored only at the start, or not at all, also matches free text that begins with a date-time, such as a note `2026-10-29T13:45:30 call back`. Without a format, `parseDate` returns no date for that text; with a format, it returns the leading date. Either way the note's text is lost. Anchor the whole value (`^…$`). +* **Partial spellings.** A pattern that accepts only some spellings of one instant (only `Z`, only three fraction digits, no `+00:00`) leaves the others as text, so the same output field is a date in one bundle and text in the next. Match every form the provider documents, for example `^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$`. +* **Several locales.** Patterns for both `MM/DD/YYYY` and `DD.MM.YYYY` guess day-first against month-first, the guess the [Rationale](#rationale) says Make cannot make. +* **Numbers.** A pattern test on a number tests its shortest decimal text: `1717243200.100` is tested as `1717243200.1`, so `/^\d{10}\.\d{3}$/` converts some values of a field and skips others. A digit count is no evidence of a timestamp either (Numerics under [Choosing the temporal meaning first](#choosing-the-temporal-meaning-first)). + +Prefer a list of the documented date fields, each converted with its documented format or unit token, such as `iml.parseDate(item.updated, 'x')` for a field the provider documents as epoch milliseconds. The list also tells you which interface fields to declare `date`. If a shape-based walker stays, declare `date` only for fields it converts in every bundle, and test each spelling the provider can send (`Z` and `+00:00`, no fraction and 3, 6 or 9 fraction digits), a text value that starts with a date-time, and a zone-less value that must stay text. A documented or sampled value that the walker loses or converts wrongly is a finding; a pattern that merely could match something unexpected is advice. + +A sketch of the list form for a response with nested records, converting only listed keys that carry a zone: + +```js +function parseDateFields(value, dateKeys) { + if (Array.isArray(value)) return value.map((item) => parseDateFields(item, dateKeys)); + if (value === null || typeof value !== 'object' || value instanceof Date) return value; + const zoned = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/; + const out = {}; + for (const [key, child] of Object.entries(value)) { + out[key] = dateKeys.includes(key) && typeof child === 'string' && zoned.test(child) + ? iml.parseDate(child) + : parseDateFields(child, dateKeys); + } + return out; +} +``` + ## Choosing the temporal meaning first Before choosing a function, name what the value is: a calendar date, a time of day, a timezone-aware date-time, a date-time with no zone, a duration, or a numeric timestamp. Each has its own contract. @@ -59,6 +95,12 @@ Before choosing a function, name what the value is: a calendar date, a time of d Polling state (what Make remembers between runs, what the epoch controls) is covered in [pagination-and-trigger-state](pagination-and-trigger-state.md); the language rules for `parseDate`, array indexing and fallbacks are in [iml-and-helpers](iml-and-helpers.md). +### Epoch units: `X` and `x` + +**Documented behaviour.** In Make's date tokens, `X` is a Unix timestamp in seconds (`1360013296`) and `x` a Unix timestamp in milliseconds (`1360013296123`). Pass the token for the unit the provider documents, in both directions: `parseDate(item.sent_at_ms, 'x')` in output, `formatDate(parameters.since, 'X')` in a request. Pass it even when the value is already a number: the IML library reads a bare number without a token as seconds (observed library behaviour, not documented), so a millisecond value parsed without `x` lands far in the future. The wrong token is off by a factor of 1000: milliseconds read with `X` land tens of thousands of years ahead, and seconds read with `x` land in January 1970. Use the same token wherever the same field is read (`trigger.date`, the epoch output, other modules). + +`formatDate` returns text. Where the provider's schema wants a JSON number, such as an epoch value, wrap the result: `{{parseNumber(formatDate(parameters.startsAt, 'x'))}}`. + ## Testing a date helper A helper that formats, parses or shifts dates is where a one-line test passes while real data fails. Trace the reachable call sites first (what the helper actually receives from the module, see [iml-and-helpers](iml-and-helpers.md)), then pick inputs that separate a correct helper from a coincidentally correct one. This is engineering guidance for helper QA, not a Make runtime rule, and it only asks for what the helper can actually be given. @@ -86,14 +128,14 @@ Make compares and sorts dates internally. A string like `03/04/2026 10:00` is am * Converting a date-only value to a datetime. That adds a midnight and a timezone nobody stated; keep it text. * Adding hours to "fix" the user's timezone for a no-timezone value. The documentation forbids using the user's or organisation's zone; the zone belongs to the provider's contract. * Declaring `order: "asc"` because the provider's default happens to be ascending, then hitting the 3200-record window on a busy account. -* Writing a helper named `normalizeDate` that only returns its input. The name proves nothing: raw ISO text through an identity helper is still unproven Date provenance (same recommendation and source ambiguity as raw output), while a traced input that is already a Date needs no change. +* Writing a helper named `normalizeDate` that only returns its input. The name proves nothing: raw ISO text through an identity helper is still unparsed text (the same finding as raw output), while a traced input that is already a Date needs no change. * Treating ISO spelling or a `date` interface as proof that a Date conversion happened. A Date and ISO text can serialize identically. * Claiming a conversion where the provider's documentation gives no format. Without a contract there is nothing to convert to; say so and keep the raw text. ## Exceptions and applicability * Output conversion and interface typing apply to emitted date-time fields; the cursor rule applies to `trigger.date`; ordering applies to polling and search/list. These are separate checks. -* Output conversion does not apply to time-only values, date-only values, no-timezone values without a documented zone (a provider-documented zone, e.g. UTC, does apply), and numerics not documented as dates (strength stays recommendation; no parse required). A documented epoch unit needs the matching interpretation. +* Output conversion does not apply to time-only values, date-only values, no-timezone values without a documented zone (a provider-documented zone, e.g. UTC, does apply), and numerics not documented as dates (strength stays recommendation; no parse required). Report a no-timezone value whose zone is undocumented as uncertain, not as a dismissal. A documented epoch unit needs the matching interpretation. * Input serialization is ISO and is its own check; do not replace calendar-date semantics with midnight UTC by habit. * Does not apply to `type: id` triggers for the parse rule, but the order rule still applies. * Epoch triggers: the epoch RPC `response.output` should carry only `label` and `date`. diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/dynamic-data-and-files.md b/skills/make-custom-apps/examples/current-knowledge/guides/dynamic-data-and-files.md index 11cc8ee..6238cce 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/dynamic-data-and-files.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/dynamic-data-and-files.md @@ -12,6 +12,58 @@ Forms that adapt to the provider at configuration time: option lists, field sche Using an options RPC where a schema is expected, or the reverse, shows the user the wrong thing or nothing. +### Request-less RPCs with conditional branches + +**Documented behaviour.** An RPC needs no request when it only returns definitions: omit `url` and return them from `response.output` (request-less communication). Communication may also be an array of requests, each with its own `condition`. A request whose condition is false is skipped, and the output of the last request is used. Together they give a fields RPC that returns a different set of fields for each value of another parameter. This is the condition-aware RPC described in [parameters and RPCs](../../../references/parameters-and-rpcs.md#condition-aware-rpcs-steps-with-condition): `required: true` inside a branch applies only while that branch is active. + +```json +[ + { "condition": "{{parameters.rangeType == 'between'}}", + "response": { "output": [ + { "name": "from", "type": "date", "label": "From", "required": true }, + { "name": "to", "type": "date", "label": "To", "required": true } ] } }, + { "condition": "{{parameters.rangeType == 'last'}}", + "response": { "output": { "name": "days", "type": "uinteger", "label": "Number of days" } } }, + { "condition": "{{!parameters.rangeType}}", + "response": { "output": [] } } +] +``` + +**Inferred implementation pattern.** + +* Reference the RPC where the documentation places dynamic fields that depend on a choice: in the controlling select's `nested` (on an option, or as `options.nested` together with `store`). If each option's fields are fixed and need no connection data, plain `nested` arrays on the options do the same without an RPC. The RPC pays off when several modules share the variants, or when a branch needs a lookup or connection data. +* Make the conditions mutually exclusive and cover every value of the controlling parameter, so exactly one branch decides the fields, or deliberately none (a branch that returns `[]` records that choice). If two conditions are true, the later branch's output replaces the earlier one and the earlier branch's fields silently disappear. A `null` output replaces nothing, so after a step that already produced a result it lets that result through ([parameters and RPCs](../../../references/parameters-and-rpcs.md#condition-aware-rpcs-steps-with-condition)). +* A branch may still call the provider (give it a `url`) when only that case needs a lookup, for example loading custom fields only once the parent is set. +* A first, request-less step can set `temp` with definitions that several branches reuse (see "Define a repeated structure once"). +* Review check: list the controlling parameter's values, confirm each has its branch, and confirm no field appears for the wrong value. If the controlling field can be mapped, its value may be unresolved while the form loads and no branch matches; make it non-mappable or handle the map path (end of "Inputs, dependencies and connection"). + +### Notices and connection-specific help from an RPC + +**Documented building blocks, inferred use.** The `banner` parameter is the documented way to show a message in a module form ([parameters and RPCs](../../../references/parameters-and-rpcs.md#banners) has its shape and when to prefer it over an `html` notice). A request-less RPC entry in a `parameters` or `expect` array can return one, so the notice can depend on other inputs or on the connection, which RPCs can read: + +* A rule that `required` cannot express, such as "set at least one of these fields", shown next to those fields. +* A step the user must take, or a warning that applies only to some connections or settings: give the branch a `condition` and return `[]` when it does not apply. +* Help that must name connection data, such as the regional base URL in a universal module's path field. The RPC returns that single field with the same `name`, `type`, `label` and `required` it would have as a static field, and builds only the help from `connection`. The help keeps the universal-module wording: the base without a trailing slash, and an example that starts with `/` and the version. It does not replace the fixed prefix in the module's own `url` ([universal-modules-and-scopes](universal-modules-and-scopes.md)). + +```json +{ "response": { "output": { + "name": "url", "type": "text", "label": "URL", "required": true, + "help": "Enter a path relative to `https://{{connection.region}}.api.example.com`. For example: `/v1/files`." +} } } +``` + +A notice informs; it does not validate. Keep the real check with the provider or in an explicit validation. + +### Option labels that are never blank + +**Inferred implementation pattern.** A label may combine several properties of the item. When the display property is optional, fall back to something the user can still recognise, usually the identifier, so a record without a name never shows up as an empty dropdown entry. `ifempty` falls back when its first argument is not defined, null or an empty string. + +```json +"output": { "label": "{{ifempty(item.name, item.id)}}", "value": "{{item.id}}" } +``` + +When the display text arrives as a map (for example keyed by locale), pick it with one deterministic rule that every RPC and helper of the app uses: a preferred key, then the first available key, then the identifier. Two RPCs that read the same object differently show different labels for the same record. The `value` stays the stable identifier either way. + ## Inputs, dependencies and connection **Documented behaviour.** Module parameters reach RPCs automatically, and nested child RPCs also inherit the parent's value. In an instant trigger's interface RPC, `webhook.` is available. An RPC with an empty parameter declaration may still read those inherited values. The RPC's connection list must match the module's, even for a request-less RPC. @@ -30,6 +82,77 @@ When a provider exposes user-defined fields: A custom function is a good place to convert provider metadata into a schema; keep it small and pure ([iml-and-helpers](iml-and-helpers.md)). +### Use the provider's capability flags, not literal lists + +**Inferred implementation pattern.** Metadata endpoints often mark each field or item with what it supports: read-only or computed, key, editable on create or update, sortable, viewable, filterable. Build each generated list from the flag that matches its purpose: + +* Create and update inputs leave out read-only and computed fields; a form that addresses a record keeps its key fields. +* A sort list offers only sortable fields, a "fields to return" list only viewable ones, a filter list only filterable ones. +* Prefer the flag to comparing identifiers with a literal list in a helper (`const unsupported = ['id-a', 'id-b']`). The list goes stale as soon as the provider adds an item, and copies of it in several helpers start to disagree. If a literal list is unavoidable, keep it in one helper, comment why each entry is there, and send an unknown identifier to the explicit fallback ("Concrete fallbacks for unsupported types" below) rather than silently into a form that may not fit. A literal list that is still accurate is a maintenance remark, not a defect. + +Users then cannot pick a field the provider rejects, and the form follows the provider without a new app version. + +### Concrete fallbacks for unsupported types + +**Inferred implementation pattern** (rule 3 above, made concrete). Two shapes were seen in approved apps: + +* **Per field.** End the type map with an explicit default instead of silently dropping the field: map an unknown provider type to `any` (listed in the editor schema; it accepts whatever the user maps) or to `text` with help that states the expected format. Add help for kinds the metadata cannot describe fully (for example a date-only field: "Date in the format `YYYY-MM-DD`."). A type left out on purpose is documented as a limitation (rule 3). +* **Per item.** When a whole selected item (a model, a record type) has no built-in form, return a `warning` banner that says so, followed by a generic array of name, type and value rows. The request folds the rows into the payload with `toCollection(parameters.extraParameters, 'key', 'value')`. Let the helper that classifies items end with an explicit "unknown" result, and give every `switch` a default that routes to this fallback. + +```json +[ + { "type": "banner", "theme": "warning", "title": "No built-in form for this item", + "text": "Add the parameters this item needs as name, type and value rows. They are sent as entered." }, + { "name": "extraParameters", "type": "array", "label": "Parameters", + "spec": { "type": "collection", "label": "Parameter", "spec": [ + { "name": "key", "type": "text", "label": "Name", "required": true }, + { "name": "type", "type": "select", "label": "Type", "options": [ + { "label": "Text", "value": "text", "nested": [ { "name": "value", "type": "text", "label": "Value" } ] }, + { "label": "Number", "value": "number", "nested": [ { "name": "value", "type": "number", "label": "Value" } ] }, + { "label": "Boolean", "value": "boolean", "nested": [ { "name": "value", "type": "boolean", "label": "Value" } ] } + ] } ] } } +] +``` + +New or unrecognised items then stay usable without a new app version, and a reviewer can see what the app does with a type it does not know. + +### A field picker for objects with many fields + +**Inferred implementation pattern.** When an object has more fields than a form can reasonably show (hundreds of standard and custom fields), let the user pick the fields first and generate inputs only for those: + +1. A multi-select (`multiple: true`) whose options come from the metadata: the value is the stable field key, the label the display name, sorted by label, with read-only fields left out. Where the options are given as an array, custom fields can sit in their own group (`grouped: true` with the grouped-options syntax). +2. `options.nested` points to a fields RPC. For a `multiple` select the nested parameters are generated for the selected options; the RPC reads the picked keys from `parameters.` and returns typed parameters for just those keys, built by the same conversion helper as any other metadata-driven field. +3. Keep the picker a plain choice (`mappable: false`): a mapped list of keys is not known while the form loads, so the nested fields could not be built. + +```json +{ + "name": "selectedFields", "type": "select", "label": "Fields to set", + "multiple": true, "mappable": false, + "options": { "store": "rpc://listWritableFields", "nested": "rpc://buildSelectedFields" } +} +``` + +The mapper stays short and the form still follows the provider's metadata. The picker is a schema-selection control, so strip it from the provider payload (rule 4). + +### Define a repeated structure once + +**Inferred implementation pattern.** Inside a fields or interface RPC, a `spec` (or a whole field list) can be filled from IML, so a structure used in several places is written once: in the `temp` of a request-less first step, or in a custom function that returns the spec array. Reference it wherever it recurs: other branches, input and output, several modules that use the same RPC. Pasted copies drift: one copy gains an option or a field type the other lacks, and two modules then accept different input for the same provider object. Give such a function a defined result for missing input (for example an empty array), because the RPC also runs while the form is still incomplete. + +```json +[ + { "temp": { "address": [ + { "name": "street", "type": "text", "label": "Street" }, + { "name": "city", "type": "text", "label": "City" } ] } }, + { "response": { "output": [ + { "name": "billingAddress", "type": "collection", "label": "Billing address", "spec": "{{temp.address}}" }, + { "name": "shippingAddress", "type": "collection", "label": "Shipping address", "spec": "{{temp.address}}" } ] } } +] +``` + +When one RPC serves several variants chosen by a non-mappable select, the variants can sit in one `temp` object keyed by the option values and be returned with `get(temp.variants, parameters.kind)`. The option values must equal the keys exactly; a mismatch returns nothing, silently. + +Copies that still agree are not a defect; report the copies that already differ. + ## Filtering and size **Documented recommendation.** Filter on the provider whenever it can; filter inside the RPC (`iterate` with a `condition`) only when it cannot, and keep dynamic RPCs inside their budget. A configuration-time list does not need to enumerate a whole large account; offer a search or mappable alternative. @@ -46,6 +169,7 @@ Dynamic forms turn a manual step (look up an ID, learn a custom schema) into an * Treating an empty RPC `parameters` list as proof that module values cannot reach it. * Leaking schema-selection controls into the provider payload. * Forgetting that a changed provider schema needs a scenario refresh. +* Reading provider metadata with the wrong key case (`item.isKey` where the metadata says `IsKey`). Property names are case-sensitive, in IML dot notation and in a custom function alike, and a property that is not defined is simply empty, with no error. A derived `required` flag or type is then silently wrong for every generated field (`IsMandatory && !isKey` is true for key fields too). Compare every referenced key, including those inside negations and fallbacks, with a real metadata response. ## Exceptions and applicability @@ -57,6 +181,8 @@ Dynamic forms turn a manual step (look up an ID, learn a custom schema) into an RPC kinds, inheritance and the connection rule: **documented behaviour / requirement**. Filtering and budgets: **documented recommendation**. The metadata handling steps are an **inferred implementation pattern**. This guide has no static fixtures, and the checker does not examine dynamic schemas. +Request-less RPCs, the request `condition`, `temp`, banners, grouped options and nested parameters for a multiple select: **documented behaviour**. Branch coverage, notices from RPCs, field pickers, capability-flag filtering, fallback shapes, single-source structures and label fallbacks: **inferred implementation patterns** seen in released apps. The checker does not examine any of them. + ## Sources * https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-options-rpc @@ -66,3 +192,11 @@ RPC kinds, inheritance and the connection rule: **documented behaviour / require * https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-sample-rpc * https://developers.make.com/custom-apps-documentation/app-components/iml-functions/dynamic-mappable-parameters * https://developers.make.com/custom-apps-documentation/best-practices/remote-procedure-calls +* https://developers.make.com/custom-apps-documentation/component-blocks/api/request-less-communication (request-less RPCs, conditional outputs) +* https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests (the request `condition` and `temp` directives) +* https://developers.make.com/custom-apps-documentation/component-blocks/api/multiple-requests +* https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/temp +* https://developers.make.com/custom-apps-documentation/block-elements/parameters (documented parameter types) +* https://developers.make.com/custom-apps-documentation/block-elements/parameters/select (`multiple`, `grouped`, nested parameters for the selected options) +* https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters (messages and banners) +* https://developers.make.com/custom-apps-documentation/block-elements/iml (`ifempty`, `get`, `toCollection`, dot notation) diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/errors-and-rate-limits.md b/skills/make-custom-apps/examples/current-knowledge/guides/errors-and-rate-limits.md index 52b6a1f..3751c52 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/errors-and-rate-limits.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/errors-and-rate-limits.md @@ -13,14 +13,91 @@ Make already treats failed HTTP calls in a sensible way. Good error handling in * `response.error.message` supplies the user-facing text. Prefer the provider's message (`{{body.error.message}}`) over a generic one; keep it free of credentials. * Per-status entries (`"400": { "type": "DataError", "message": "..." }` and similar) change the type and message for one status. The Error reference requires every status-code specification to contain `message`; `type` is optional. A per-status object that has only `type` does not match that documented shape, and the generic top-level `message` does not satisfy it. (This is an authoring-contract point from the reference; static review does not prove how the runtime treats an object without `message`.) A per-status specification takes precedence over the generic `message` and `type`; when it omits `type`, the generic `type` applies, and when there is none, the default for that HTTP status. * A generic `type` set at the top level of `response.error` **overrides** the default type mapping, including the 429 and 5xx defaults. That is easy to do by accident: setting one generic type to improve a message can turn rate limits into ordinary errors. Prefer per-status entries and leave the statuses you do not understand to the defaults. +* **Documented error shapes.** When the provider documents an error body (4xx bodies, including 422 validation errors, with a message or a list of field errors), handle it in Base `response.error` or the module, consistent with the provider's documented shape and without a generic `type`, so the user sees that message and the 429 and 5xx defaults stay. Do not leave a documented shape to the generic default. * Error text belongs to the error directive, never to `output`. +### Pick an override type by what it does to the scenario + +**Documented behaviour.** The type decides how the scenario reacts, so an override changes behaviour, not just a label ([error types](https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/error#error-types)): + +| Type | What Make does with the scenario | Fits | +| --- | --- | --- | +| `RuntimeError` (default for 4xx other than 429) | Interrupts the run; turns the scenario off only after the consecutive-error limit (3 by default) | A request that will fail again unchanged | +| `DataError`, `DuplicateDataError` | Stores the bundle as an incomplete execution when the user enabled that, so the data can be fixed and the run resumed; otherwise behaves like `RuntimeError` | Input the provider rejected for this one record | +| `RateLimitError` (default for 429) | Suspends the scenario for a delay (about 20 minutes by default), then resumes it; does not count as a consecutive error | Throttling that waiting resolves | +| `ConnectionError` (default for 5xx) | Retries on a later run with a backoff delay; deactivates the scenario when it keeps failing | Outages and temporary server errors | +| `InvalidAccessTokenError`, `InvalidConfigurationError` | Deactivates the scenario and notifies the user | Credentials that no longer work; an account or connection setup the user must change, never one rejected record | + +* Map `InvalidAccessTokenError` only to a status the provider uses for invalid, expired or revoked credentials, usually 401. The override is optional: leaving 401 on its default `RuntimeError` is also correct. Many providers also answer 403 when the credentials are fine but the user lacks a role, a permission or a plan feature for this record or call (no access to this record, a feature or region not enabled for the account). Mapping that 403 to `InvalidAccessTokenError` switches off a scenario whose connection is healthy and sends the user to re-authorise, which fixes nothing. Leave such a 403 on its default `RuntimeError` with the provider's message, or compute the type from the provider's error code when the same status covers both causes (see "Computing the type from the response"). +* Do not map 401 or 403 to `ConnectionError`. Make then retries, with growing delays, a request that cannot succeed until someone reconnects or changes permissions, and deactivates the scenario only after all the retries. + +```json +"error": { + "message": "[{{statusCode}}] {{body.error.message}}", + "401": { "type": "InvalidAccessTokenError", "message": "[{{statusCode}}] {{body.error.message}}" }, + "403": { "message": "[{{statusCode}}] {{body.error.message}} Check that the connected user may access this record." } +} +``` + +### Computing the type from the response + +`type` is an IML expression, like `message`: the generic one, each per-status one and `valid.type`. Compute it when one status carries several causes, for example a 403 that means a revoked token for one error code and a missing permission for another. Keep such expressions safe: + +* Base the decision on what the error response carries: `body`, `statusCode` and `headers`, which are the **response** headers. A header the module sent is not there. A condition on a field the provider never returns always takes the same branch, so the reclassification never happens; check every branch against a real or documented error response. +* Prefer the provider's structured error code (`body.error.code`, a GraphQL `extensions.code`) to matching text in the message. A `contains()` on a phrase breaks when the wording changes or is translated, and a rate limit then silently becomes an ordinary error. +* Return only names from the error-types list. A made-up name such as `ValidationError` is not a Make error type, so the handling it was meant to select never happens; the editor schema cannot see a wrong name inside an expression. +* A computed **generic** `type` still replaces the defaults for every status. If its last branch returns `RuntimeError` or `DataError`, 429 and 5xx lose `RateLimitError` and `ConnectionError`. Put the expression under the status it is about, or end it with the defaults. +* Use `if()` or `switch()`. IML has no `? :` operator; `{{a ? 'x' : 'y'}}` produces text, not a choice. + +```json +"403": { + "type": "{{if(body.error.code = 'token_revoked', 'InvalidAccessTokenError', 'RuntimeError')}}", + "message": "[{{statusCode}}] {{body.error.message}} ({{body.error.code}})" +} +``` + +A generic version that keeps the defaults for everything it does not recognise: + +```json +"type": "{{switch(body.code, 'invalid_api_key', 'InvalidAccessTokenError', 'rate_limited', 'RateLimitError', if(statusCode = 429, 'RateLimitError', if(statusCode >= 500, 'ConnectionError', 'RuntimeError')))}}" +``` + +### Building the message from the provider's error shape + +* **Lists of errors.** Show all of them: `{{join(map(body.errors, 'message'), '; ')}}`. Empty brackets in a path, such as `{{body.errors[].message}}`, do not list anything; they return the first error's message only. +* **Field details.** When each error names a field or a code, include it (`email: is invalid`) so the user knows which input to change. For nested objects of field errors, use a small helper that walks the documented structure and returns one `path: message` line per entry. Such helpers are custom IML functions, which are not enabled for every app; confirm access first ([IML functions](../../../references/iml-functions.md)), and otherwise render the documented fields with built-in functions. Call it with the error object and keep the status in the template: `"[{{statusCode}}] {{formatFieldErrors(body.error)}}"`. +* **Bodies that are not the documented JSON.** Gateways and outages often return an empty, text or HTML body. On a text body any path below `body` (such as `body.error.message`) returns the whole text, and `map()` fails because the value is not an array, so the user sees a function error instead of the status. Keep list rendering in the per-status entries whose body the provider documents as JSON (typically 400 and 422), or in a helper that checks `Array.isArray` and returns a fixed text for `null`, strings and unexpected shapes. A helper that throws replaces the provider's error with its own. +* **Fixed paths, not searches.** Read the documented error paths. Do not stringify the body and extract values with regular expressions, or search the whole body for the first key whose name looks like an error: such searches stop at escaped quotes, break when keys are reordered, and can pick up an unrelated field. +* **Hints after the provider text.** A fixed message such as "Access denied." or "The API key is inactive." is a guess when one status has several causes; it hides the real cause and any request ID that support needs. Append the hint instead: `"[{{statusCode}}] {{ifempty(body.error.message, 'No details returned.')}} Check that the connected user can access this record."` +* Test message helpers with each documented error body, a `null` body, a text body and a body without the expected fields, and assert exact strings. + ## Failures inside successful responses **Documented behaviour.** A 2xx or 3xx response is not an error by default. If the provider signals failure with a 200 and an envelope (`{ "ok": false, "error": ... }`), use the `valid` directive to declare when the response is valid. Per-status error entries for 200-399 only fire after `valid` has marked the response invalid. Also check batch results: a bulk call can return overall success with per-item failures, and the module must define whether it reports overall or item-level outcomes according to what the provider supplies. A field named `error` in a success response is not automatically a failure; it may be informational. Read the provider contract and a real response before writing `valid`. +**Documented behaviour.** An error raised through `valid` takes its type from `valid.type`, then `response.error..type` (for example `"200"`), then the generic `response.error.type`, and otherwise `RuntimeError`. The 429 and 5xx defaults never apply, because the HTTP status is a success status. When the provider reports throttling or a temporary outage inside a successful response, such as a GraphQL error code for a rate limit, set that type explicitly; otherwise a rate limit counts toward the consecutive-error limit instead of pausing the scenario. Put the type next to the message: on `valid.type` when `valid` sets its own `message`, otherwise on the status entry. + +```json +"response": { + "valid": "{{!body.errors}}", + "error": { + "message": "[{{statusCode}}] {{body.message}}", + "200": { + "type": "{{if(body.errors[1].extensions.code = 'RATE_LIMITED', 'RateLimitError', 'RuntimeError')}}", + "message": "[{{statusCode}}] {{join(map(body.errors, 'message'), '; ')}}" + } + } +} +``` + +**Batch envelopes.** A batch call (a multipart batch, or an array of sub-results) can answer 200 for the envelope while each item carries its own status, and Make only sees the envelope. When the module fails on item errors: + +* Read each item's status together with the key the provider echoes for it (a content ID, request ID or reference), and match results to requests by that key, not by position. +* Mark the response invalid in `valid` and list every failing item with its key, code and message in one error, not only the first. +* Choose the type with the items that already succeeded in mind. A retrying type (`ConnectionError`, `RateLimitError`) can send the whole batch again and repeat those items; use it only when every item failed for that reason or the provider documents the batch as atomic or safe to repeat. Otherwise keep the default and name the items that were applied. + ## Errors in multi-step communication An HTTP error in one request of a request array cannot be turned into success by a later request, so decide the error policy per request. Do not build a flow that expects an optional lookup to fail quietly; if a step may be unnecessary, make it conditional or split it into its own module. See [requests-files-multistep](requests-files-multistep.md) for sequences and repeats. @@ -43,6 +120,21 @@ Budget requests, paginated records, time and the provider's own limits together. The example sets a generic message and one per-status specification that carries its own sanitized `message` and a `type`, and deliberately does not set a generic `type`, so 429 and 5xx keep their defaults. +### Exhausted credits, quotas and plan limits + +A used-up balance is not a rate limit: credits that must be bought, or a feature missing from the plan, do not come back by waiting. + +* Keep a type that does not retry; the 4xx default `RuntimeError` fits. `RateLimitError` would pause and resume the scenario again and again without counting toward the error limit, and `ConnectionError` would retry with backoff a request that cannot succeed. A quota that resets on a documented schedule (per minute or per day) is the case where `RateLimitError` fits. +* After the provider's own text, say what ran out, who can fix it (an account admin, the plan owner) and that running again will not help until then. +* Detect every shape the provider documents for the same condition: a 402, a 403 or 429 with a specific error code, or a 200 whose body carries the message. Keep the check in one helper or expression, use it in `valid` and in the per-status entries, and use the same wording in every module. +* If the provider uses one status (often 429) for both throttling and an exhausted balance, compute the type from the documented error code (see "Computing the type from the response"). + +```json +"402": { + "message": "[{{statusCode}}] {{ifempty(body.error.message, 'The account has no credits left.')}} An account admin must add credits; running the scenario again before that fails the same way." +} +``` + ## Rationale The platform's defaults encode what the scenario engine needs (retry for rate limits, connection errors for outages). Overriding them wholesale trades that for a slightly nicer message. Because many providers also return failures with status 200, the `valid` directive exists to make the success definition explicit instead of inferred. @@ -56,6 +148,14 @@ The platform's defaults encode what the scenario engine needs (retry for rate li * Passing business failures through as ordinary output bundles. * Putting secrets, tokens or full request bodies into error messages. * Expecting a later request in the same communication to rescue an HTTP error. +* Mapping a 403 that means "no permission for this record" to `InvalidAccessTokenError`, or 401/403 to `ConnectionError`. +* A computed error type that tests a field the error response never carries, returns a name outside the error-types list, or ends in a fallback that drops the 429 and 5xx defaults. +* Leaving a rate limit reported inside a 200 to the `RuntimeError` fallback of `valid`. +* Using `{{body.errors[].message}}` as if it listed every error. +* Rendering an error list with `map()` in a message that also handles non-JSON gateway bodies. +* Matching batch item results to requests by position, or giving a partly applied batch a type that retries it. +* Mapping exhausted credits or plan limits to `RateLimitError` or `ConnectionError`. +* Replacing the provider's message with a fixed guess instead of appending a hint. ## Exceptions and applicability @@ -68,6 +168,9 @@ The platform's defaults encode what the scenario engine needs (retry for rate li * Default statuses, directive names and the `valid` interaction: **documented behaviour** (error handling, response `valid` and `error` pages). * Which provider responses count as failures: **provider contract**; verify with real error responses. * This guide is not covered by the static checker; real error cases belong in the review evidence described in [compatibility-evidence](compatibility-evidence.md). +* Error-type consequences, `type` as an IML expression and the `RuntimeError` fallback for errors raised through `valid`: **documented behaviour** (error and valid pages). +* Empty brackets returning the first array element, a path below a text body returning the text, `map()` failing on a non-array and `? :` producing text: **not documented** (not stated on a public page); confirm with a real error response in the Make DevTool before relying on it. +* Whether a 403 means invalid credentials or a missing permission, which code marks an exhausted balance, and whether a batch is atomic or safe to repeat: **provider contract**. ## Sources @@ -77,3 +180,5 @@ The platform's defaults encode what the scenario engine needs (retry for rate li * https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/valid * https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests * https://developers.make.com/custom-apps-documentation/create-your-first-app/error-handling +* https://developers.make.com/custom-apps-documentation/best-practices/modules/batch-actions +* https://developers.make.com/custom-apps-documentation/block-elements/iml diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/headers-merge.md b/skills/make-custom-apps/examples/current-knowledge/guides/headers-merge.md index 0202c2e..7a91ff6 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/headers-merge.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/headers-merge.md @@ -19,6 +19,36 @@ Authentication usually lives in the Base `headers`. A module that adds a header } ``` +### Dropping one inherited header in one request + +**Inferred implementation pattern** (it combines the documented per-name merge above with the input-parameters page's examples, where a value of `undefined` leaves the key out of the request body). To keep one request from sending a single Base header, keep `headers` a collection and set that name to `"{{undefined}}"`. The module entry wins by name, its value evaluates to `undefined`, and the header is left out of the request. Every other Base header, including the credential, is still sent. + +```json +{ + "headers": { + "x-api-version": "{{undefined}}" + } +} +``` + +Use it when the provider documents that one endpoint, or one endpoint family, rejects or misreads a header the rest of the API needs (a version header, for instance), or when one endpoint takes the same credential in a different place from where Base sends it: + +```json +{ + "headers": { + "authorization": "{{undefined}}" + }, + "qs": { + "access_token": "{{connection.accessToken}}" + } +} +``` + +* Write the name the way Base writes it. Names are case-insensitive, but the same spelling keeps the effective set obvious and does not depend on how case-variant collisions resolve (see Evidence and limits). +* Move the credential only where the provider requires that placement for the endpoint, and mask its new location: add the path (here `request.qs.access_token`) to Base `log.sanitize`, which every module inherits ([auth-context](auth-context.md)). As a reviewer, a placement the provider accepts is not a defect; a missing `log.sanitize` path for it is fixed as credential masking. +* When computing the effective headers, remove every name whose module value is `undefined`. +* This is narrower than the alternatives. A whole-expression `headers` value drops all of Base, and repeating the whole Base set in the module copies the credential into every such module (see Pitfalls). A reviewer does not flag the dropped name as "ignoring Base" and does not replace it with a full override. + ## Computing the effective headers Do it in this order and write the result down: @@ -40,6 +70,7 @@ The checker's `CK-HEADERS-MERGE` rule does this computation over a declared fixt * **Absolute URLs.** An absolute request URL does not by itself prove that inherited authentication is lost. Check which configuration the documented context applies and what the effective request carries. The security question for user-supplied destinations is separate (see [universal-modules-and-scopes](universal-modules-and-scopes.md)). * **Customisable headers on universal modules.** Two independent checks. *Customisation:* the documented REST universal example exposes an optional Headers array mapped into the request headers, so assess header capability for every REST universal module, not only once a provider is already known to need one. Any equivalent mapped input counts; no parameter name is mandated. A missing REST capability is at least a documented-convention recommendation; being unable to send a header the provider requires (a version or content negotiation header) is a concrete, scoped capability defect. It is not an unqualified publication blocker: the GraphQL universal example has query/variables inputs and no Headers input (its Headers field is output), so the generic REST Headers-input convention is not by itself a GraphQL finding. That does not exempt provider-required headers: independently check that any header the provider requires can be sent (the official GraphQL example sets a request header in Communication). *Authentication:* trace whether the effective request keeps the credentials. Missing customisation never shows auth was lost, and a spread does not by itself prove every credential collision safe. Input headers and response headers are different things. * **Pagination and repeats.** Pagination merges parent request parameters by default, and overriding only the URL does not make other inherited values vanish ([pagination-and-trigger-state](pagination-and-trigger-state.md)). +* **Signed and external file URLs in a request chain.** An absolute URL replaces only the Base URL, so the Base headers, credential included, still go with a step that calls a URL the API returned on another host. When and how to drop the credential on that step only (by name, with `"{{undefined}}"`), and how a reviewer treats it: [requests-files-multistep](requests-files-multistep.md#a-follow-up-request-to-a-url-the-provider-returned). ## Rationale @@ -53,18 +84,21 @@ The spread exists precisely so that a computed set of headers can be added witho * Re-adding the token by hand in every module. When the credential changes, the modules silently disagree. * Putting credentials in `qs` for convenience; then they appear in URLs and logs. * Mixing `qs` and a query string in the URL; use one. +* Reading the module template's empty `"headers": {}` as clearing the Base headers, either to keep the credential off one step or as a finding that the module lost authentication. An empty collection merges, so every Base header, credential included, is still sent; that boilerplate is not a finding. +* Blanking an inherited header with `""`, or setting `"headers": null`, to stop it being sent. Neither is documented to remove a header, so new code sets the one name to `"{{undefined}}"` instead (see *Dropping one inherited header in one request*). In review, an existing blank or `null` on a step that works is not a finding. What `"headers": null` does to the rest of Base is not documented, so do not claim from it alone that the credential is kept off or that it leaks. ## Exceptions and applicability * Applies to modules and RPCs that inherit Base. A universal module must use a relative path so that tokens cannot be redirected to another host; a header merge does not change that. * A whole-expression override is legitimate for an unauthenticated provider endpoint or a sign-in call; in that case the missing Base auth is intended. -* A fixed `baseUrl` containing a path is not changed by a suffix in the module URL pointing elsewhere. +* A fixed `baseUrl`, with or without a path, does not on its own keep a user-supplied module URL on the provider host: a complete URL in the input is treated as absolute. A universal module puts its own fixed prefix, ending with `/`, directly before the input ([universal-modules-and-scopes](universal-modules-and-scopes.md)). ## Evidence and limits * Merge, overwrite and case-insensitivity: **documented requirement** (documented behaviour). * Replacement versus merge and case-insensitive names are what the checked primary pages establish. The within-collection "apply entries in order, later write wins" step (and mixed spread/explicit or case-variant collisions) is a **bounded fixture model, not proven platform precedence**: do not use it alone to assert an authentication failure; seek explicit documentation or runtime evidence first. * The modelled effective-headers computation: **inferred implementation pattern**. The checker takes `spreadProduces` from the fixture; it never evaluates the helper that would really produce the headers, and it does not model every IML edge case. +* Dropping one inherited header with `"{{undefined}}"`: **inferred implementation pattern**. It combines the documented per-name merge with the input-parameters page's examples, where `undefined` leaves a key out of the request body. The headers reference itself does not mention `undefined`; do not extend the rule to `""`, `null` or an empty collection, which are not documented to remove a header. ## Fixtures diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/iml-and-helpers.md b/skills/make-custom-apps/examples/current-knowledge/guides/iml-and-helpers.md index 2af18f1..7a088b9 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/iml-and-helpers.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/iml-and-helpers.md @@ -18,6 +18,61 @@ An app has two expression worlds. **IML** is the expression language inside `{{ Use helpers for work that would otherwise obscure communication: converting provider metadata into a dynamic field schema, normalising nested values, converting a date, or applying a provider-specific encoding. Keep them deterministic, small and explicit about inputs and outputs, and test missing, empty, zero, false and malformed values. +### Recursive cleaners and array elements + +See [outputs, empty values and updates](outputs-empty-values-updates.md#recursive-cleanup-helpers-check-every-branch) — what a recursive empty-value cleaner, including the documented one, does to array elements, dates and buffers, and a corrected version with its tests. + +### Helpers that build query text or JSON text + +A `filter` parameter returns an array of condition groups. The groups are joined by OR and the `{ a, o, b }` conditions in a group by AND; an operator that needs no value has no `b`. The [filter documentation](https://developers.make.com/custom-apps-documentation/block-elements/parameters/filter) converts that value to the provider's query syntax in a custom function. Such converters decide whether user values arrive intact, and so do helpers that assemble a key predicate or a JSON string: + +* **Serialise JSON with `JSON.stringify`.** A template such as `` `{"${key}": "${value}"}` `` produces invalid JSON as soon as a value contains a quote, a backslash or a line break, and it lets a value add keys. Build an object and stringify it. +* **Escape literals the way the provider's syntax documents.** `` `${field} eq '${value}'` `` breaks on an apostrophe and lets a value change the query. Many query syntaxes escape a single quote by doubling it, but check the provider's own rule ([user values inside provider query languages](../../../references/requests-and-responses.md#user-values-inside-provider-query-languages)). Quote by the field's declared type (text quoted, numbers and booleans bare), not by whether the value looks numeric. Where the provider accepts values separately (GraphQL variables, a JSON body), pass them there instead of splicing them into the query text. +* **Convert every group and every offered operator.** The documented example reads only the first group, which fits its `logic: "and"` setting; a filter that allows OR must convert every group. Give each offered operator, negations included, its own branch: a negated operator (`not contains`) that shares the positive branch silently returns the opposite records. A `switch` without `default` returns `undefined`, which `join` turns into an empty condition and a template literal turns into the text `undefined`. Map operators through an explicit table and throw on an unknown one. + +Test a value containing a quote, a backslash and a line break, every offered operator, an unknown operator and, where OR is allowed, two groups. + +```js +// quote by the operator's value type, not by the JavaScript type of b: +// a filter's b can arrive as text even when the user typed a number +const text = (v) => `'${String(v).replace(/'/g, "''")}'`; + +const OPERATORS = { + 'text:equal': (field, value) => `${field} eq ${text(value)}`, + 'text:startwith': (field, value) => `startswith(${field}, ${text(value)})`, + // one entry per offered operator, negations included; a numeric operator converts and + // checks its value instead of quoting it; an operator without b ignores value +}; + +function toCondition({ a, o, b }) { + if (!Object.prototype.hasOwnProperty.call(OPERATORS, o)) throw new Error(`Unsupported filter operator: ${o}`); + return OPERATORS[o](a, b); +} + +// JSON text: build an object, never a template +const toFilterJson = (key, value) => JSON.stringify({ [key]: value }); +``` + +### Whole-response normalisers that convert by value shape + +See [dates-helpers](dates-helpers.md#helpers-that-decide-by-value-shape) — what a helper that converts every date-looking value gets wrong (zone-less values, prefix matches, partial spellings, numbers) and the list-of-date-fields form that avoids it. + +### Parsing JSON the user typed + +When a helper parses text that a user typed or mapped, such as an advanced JSON field or a "properties as JSON" option, wrap `JSON.parse` and throw an error that names the field and says what is expected. An unguarded parse fails the run with a generic parser message (an unexpected token at some position), which does not tell the user which field to fix. Parse only text: a value that is already an object passes through. Test invalid JSON, an empty string and an already parsed object. + +```js +function parseJsonField(text, label) { + if (text === undefined || text === null || text === '') return undefined; + if (typeof text === 'object') return text; + try { + return JSON.parse(text); + } catch (e) { + throw new Error(`${label} must be valid JSON: ${e.message}`); + } +} +``` + ## Tracing a helper A helper is useful only if the data travels through it and it changes the value. Follow four links: @@ -31,10 +86,47 @@ Hidden components belong in the inventory too. Hidden visibility does not make a Do not use a number's magnitude, an identifier's type name or a parameter name as dependency proof. The dependency is shown by a reference in the definition graph, not by a guess about what a value "must be". +### Effects through mutation + +A helper can act by changing an object it was given instead of returning a new one: it assigns or deletes keys on its argument, or on the items of an array argument. Within one function's code the caller then sees the change even if it ignores the return value. Whether a change made by another custom function, called through `iml.`, reaches the caller is not documented. This has two consequences: + +* **Tracing.** Before you report a helper call as not consumed because its return value is unused (link 4), check whether the helper mutates an argument that the caller keeps using. If it does, the effect is invisible at the call site; settle it with an editor test or an execution, not from the call site alone. +* **Authoring.** Return a new value and use it at the call site, or copy before editing. A helper that edits its input in place gives a different result when the same object is processed twice. That happens with a repeated call, a recursive walk that reaches a shared object again, or a test that reuses one fixture for two assertions: the second pass sees already converted values or keys already deleted. When the contract is non-mutating, add a test that the input is unchanged after the call. + +```js +// effect hidden in the argument: the call site looks like it does nothing +iml.dropEmptyArgs(parameters); +return { name: parameters.name, items: parameters.items }; + +// effect visible at the call site +const args = iml.dropEmptyArgs(parameters); // returns a new object +return { name: args.name, items: args.items }; +``` + ## A small pure helper, in prose A date normaliser takes the provider's string, checks that it matches the documented format, converts it to an ISO timestamp, and returns nothing (or fails clearly) for input it cannot parse. It has no network, no timezone guessing and no shared state. The call site passes the provider's field, and a test covers a valid value, an empty value and a malformed value. +Two habits break that purity without looking wrong: + +* **Declare every variable** with `const` or `let`. An assignment to an undeclared name (`date = …`, `config = { … }`) does not create a local. In non-strict JavaScript it writes a global that can outlive the call and be seen by later calls and by other helpers sharing the runtime. In strict-mode code (ES modules and many local test runners) it throws a `ReferenceError` instead (standard JavaScript strict-mode behaviour; MDN Web Docs, strict mode). Either way the helper has shared state, and the same file can behave differently in a local test and in Make. +* **Check a lookup before dereferencing it.** `match` and `exec` return `null` when nothing matches, and `find` returns `undefined`. So `value.match(re)[1]` or `text.match(re).map(…)` throws on the first value with an unexpected shape, and the whole module run fails with the function's error. In a helper that walks every field of a response, leave a non-matching value unchanged. + +```js +const match = typeof value === 'string' ? value.match(pattern) : null; +if (!match) return value; // leave an unexpected shape unchanged +const timestamp = match[1]; +``` + +Regular expressions can carry hidden state too. A pattern with the `g` (or `y`) flag makes `test()` and `exec()` start at its `lastIndex` and move it after every match. Reusing one such object across several values, in a loop over entries or a `map` over an array, makes the next `test()` start in the middle of the next string, so a matching value can be reported as not matching. A following `replace()` resets `lastIndex`, which can hide the problem until someone removes that call (standard JavaScript behaviour; MDN Web Docs, `RegExp.prototype.test`). For a yes/no check, use a pattern without `g`, and keep `g` for `replace` or `matchAll` over one string. A literal written inside the function body is created anew on each call, so the risk is one object reused within a call, or a pattern stored outside the function body, which can be shared between calls. + +```js +const iso = /^\d{4}-\d{2}-\d{2}$/g; +['2024-01-01', '2024-01-02'].map((v) => iso.test(v)); // [true, false] + +const isIsoDate = /^\d{4}-\d{2}-\d{2}$/; // yes/no check: no g flag +``` + ## Testing a helper This is engineering guidance for helper QA. The [IML tests page](https://developers.make.com/custom-apps-documentation/get-started/make-apps-editor/apps-sdk/iml-tests) documents the editor's `it(name, fn)` tests and strict and deep assertions; it does not mandate any of the coverage below. @@ -80,6 +172,22 @@ test('0 is out of range, not "missing"', () => { A local test with a mock runs your function in Node. It is not proof of how Make runs it, of the available built-ins, or of the editor's behaviour; report it as a local unit test and use an editor test or an execution when the Make runtime is the question. +`assert.throws` has the same trap shape as `assert.ok`. In Node.js `assert` (listed under Sources) its second argument is an optional error validator and its third argument is only the failure message. The editor page lists the signature as `assert.throws(fn, [error])`. None of these forms checks the error the test is named after: + +* `assert.throws(fn)` with no validator passes for any error. That includes a `TypeError` from a crash before the helper reaches its own check. +* A class alone, as in `assert.throws(fn, TypeError, 'input is missing')`, passes for every error of that class. The string is never compared with the thrown message. With `Error` as the class, any thrown error object passes. +* A string as the second argument is not a validator either. Node treats it as the failure message. +* A misplaced closing parenthesis, as in `assert.throws(() => { fn(bad, TypeError, 'msg'); })`, turns the class and the message into extra arguments of the helper. Nothing is validated. + +Pin the error with a regular expression or with an object holding `name` and `message`, so that a different error fails the test. Node tests a regular expression against the error's `Name: message` text, so anchor it with `^` and `$` when the exact message is the contract. The editor page documents no validator form beyond `[error]`: before relying on one there, change the expected message once and confirm that the test fails. The helper below is illustrative. + +```js +it('rejects a response without items', () => { + assert.throws(() => normalizeResponse({}), /^TypeError: "response\.items" is missing\.$/); + assert.throws(() => normalizeResponse({}), { name: 'TypeError', message: '"response.items" is missing.' }); +}); +``` + ## Rationale IML keeps communication declarative and reviewable; helpers are an escape hatch with a smaller, different runtime. Keeping each in its own lane makes expressions readable and makes helper failures easy to localise. @@ -94,6 +202,14 @@ IML keeps communication declarative and reviewable; helpers are an escape hatch * Concluding a value is a timestamp or an identifier from its digits. * Passing `assert.ok(result, expected)` and believing `expected` was compared, or testing only inputs the call sites never send. * Reporting a local mock test as proof of Make runtime behaviour. +* Reading `assert.throws(fn, TypeError, 'message')` as a check of the message, or writing `assert.throws(fn)` with no validator. +* Reusing a recursive empty-value cleaner (including the documented one) without checking that primitive array items and `Buffer` values survive and that emptied elements are removed rather than sent as `{}` or `null`. +* Building JSON or provider query text with template strings around user values, converting only the first group of a filter that allows OR, or letting a negated operator share the positive branch. +* Converting every date-looking string in a response, including free text that only starts with a timestamp. +* Calling a helper call unused without checking whether the helper mutates its argument, or relying on such a mutation instead of a returned value. +* Assigning to an undeclared variable, or indexing the result of `match`, `exec` or `find` without checking it. +* Parsing user-typed JSON without an error that names the field. +* Calling `test()` repeatedly on one regular expression that has the `g` flag. ## Exceptions and applicability @@ -107,6 +223,8 @@ IML keeps communication declarative and reviewable; helpers are an escape hatch * The helper-testing steps (exact assertions, boundaries, timezones): **engineering guidance**, not a documented Make requirement; only `it(name, fn)` tests and the assertion style come from the editor documentation, and Node's assert semantics come from the Node.js documentation. * The four-link trace: **inferred implementation pattern**; the checker's textual version in [dates-helpers](dates-helpers.md) never executes a helper. * Runtime behaviour needs runtime evidence, and a helper test in the debugging tools is one good source. It is not the only one: a module or RPC run that exercises the helper, an IML test file, or a scenario execution also shows what the function returns. Choose evidence that covers the real call path and the missing, empty, zero, false and malformed inputs. +* `assert.throws` argument semantics: **Node.js documentation**; the editor page only lists `assert.throws(fn, [error])`. `lastIndex` state and undeclared assignments in strict and non-strict code: **standard JavaScript behaviour** (MDN), not Make sources. The array and `Buffer` behaviour of the documented empty-removal helper is read from its published code. The filter value's groups, conditions and OR/AND joining are **documented behaviour** (filter parameter page). +* Escaping and operator coverage in query builders, value-shape normalisers, mutation and guarded JSON parsing: **engineering guidance** drawn from recurring helper patterns, not documented Make requirements. Whether a mutation crosses an `iml.` call between custom functions is **not documented**. A demonstrably wrong value is still a finding; a style difference alone is not. ## Sources @@ -116,3 +234,7 @@ IML keeps communication declarative and reviewable; helpers are an escape hatch * https://developers.make.com/custom-apps-documentation/debug-your-app/debugging-of-custom-iml-functions * https://developers.make.com/custom-apps-documentation/get-started/make-apps-editor/apps-sdk/iml-tests * https://nodejs.org/api/assert.html (strictEqual, deepStrictEqual, throws and ok semantics for local Node tests; not a Make source) +* https://developers.make.com/custom-apps-documentation/app-components/iml-functions/removal-of-empty-collections-and-nulls (the documented recursive removal helper and its array handling) +* https://developers.make.com/custom-apps-documentation/block-elements/parameters/filter (filter value structure and converting operators in a custom function) +* MDN Web Docs, `RegExp.prototype.test` (`lastIndex` with the `g` flag; not a Make source) +* MDN Web Docs, strict mode (undeclared assignments; not a Make source) diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/interfaces-required.md b/skills/make-custom-apps/examples/current-knowledge/guides/interfaces-required.md index d284846..785bf77 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/interfaces-required.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/interfaces-required.md @@ -28,6 +28,8 @@ Where that comparison establishes an applicable, unmet input requirement, record Both points are mostly form-quality guidance: a more accurate type or clearer help for a field that already works is a recommendation, not a blocker, and an existing app's types should not be changed in place without checking what its saved scenarios already map. That does not downgrade a demonstrated defect. A type the schema rejects, a declared type that loses or alters the value, a `required: true` that blocks a valid state, or a mismatch with documented provider behavior is a concrete finding when the evidence is cited, even though adjacent layout advice stays advice. The date-only and time-only `text` exception above is unchanged. +**Alternative inputs.** "Either field A or field B is required" is one of the conditionally required cases the mappable-parameters best practices name, and a clear hint is mandatory for it. Marking every alternative `required: true` forces the user to fill all of them. Use a branch structure as described above where one fits. Otherwise leave the alternatives optional and put the rule in the help of each one, naming every alternative ("At least one of **Email** or **Phone** is required."), because a user who maps one field reads only that field's hint. Alternatives whose hints name the rule are not "optional but actually required"; a missing hint is the conditional-help gap in the approval impact below and stays advisory. + ## Falsy values and empty values **Documented recommendation.** The input-processing page recommends `"body": "{{parameters}}"` or `"{{...}}": "{{omit(parameters, 'id')}}"` and says that using `ifempty(..., undefined)` or an `if` to drop empty values is a bad practice, since `null`, empty string, `0` and empty arrays could then never be sent. On platform version 2 empty values are already ignored by default; update and universal modules show an `erase` pill so users can send an explicit empty value. @@ -44,7 +46,7 @@ Both points are mostly form-quality guidance: a more accurate type or clearer he For a known provider response contract, compare **provider response → actual emitted user-facing object → declared interface**, including raw outputs. Follow wrappers, iteration and flattening to the object actually emitted. Enumerate each known in-scope property's disposition: declared with matching name and type, deliberately excluded with a request-scope, privacy or output-design basis, or retained but undeclared. The last is a declaration gap, not proof of data loss or unmappability. For dynamic or unknown collections, use the documented generic shape instead of inventing properties. -A known useful field included in the selected output contract still needs the appropriate interface declaration and type when raw output retains it. Report the declaration defect without inventing data loss or unmappability. Keep declaration and conversion judgments separate: preserve date-only and undocumented-zone exceptions, and do not demand redundant parsing for an already conforming ISO value with a matching date interface. Deliberate, justified scope exclusions and unknown or dynamic collection shapes remain valid. +A known useful field included in the selected output contract still needs the appropriate interface declaration and type when raw output retains it. Report the declaration defect without inventing data loss or unmappability. Keep declaration and conversion judgments separate: preserve date-only and undocumented-zone exceptions, and otherwise parse an output date-time with the provider's format even when it is already ISO: a matching date interface does not convert it, and marketplace review treats the unparsed value as Required. Deliberate, justified scope exclusions and unknown or dynamic collection shapes remain valid. ```json { @@ -53,6 +55,13 @@ A known useful field included in the selected output contract still needs the ap } ``` +**Inferred implementation pattern.** Names are unique per level and compare exactly, case included. Run the name comparison above on every level, nested `spec` levels included, in static interfaces and in interfaces an RPC builds: + +* **Twins.** Two entries with the same `name` at one level describe one key of the emitted object, so at most one of them can be right. Besides merged response variants ([outputs-empty-values-updates](outputs-empty-values-updates.md)), a common cause is a copied entry that kept its original name, such as an entry labelled "Line 2" that still has the name of "Line 1". Two inputs that share a name in one parameter list likewise compete for one key of `parameters`. +* **Case variants.** An entry `accountID` next to an emitted `accountId` names a key the output never carries. Keys match exactly, so a value mapped from that entry is empty while the real key stays undeclared. + +Both usually arrive with a long interface or parameter list copied from a sibling module, which can also bring fields that only the other resource returns. For interfaces, impact follows the approval rules below. An identical twin, or one that differs only in a scalar type, is advisory cleanup. A twin whose type contradicts the emitted container, or a case variant the output never carries, is a wrong key and is fixed. For a parameter twin, judge impact from the value the request actually receives. + ## Related output and input details * **Precision.** A provider identifier too large for a JSON number can be rounded when the response is parsed, and declaring the interface field as `text` afterwards cannot restore digits. If the provider cannot send such identifiers as strings, use the documented response-parsing option before precision is lost ([outputs-empty-values-updates](outputs-empty-values-updates.md)). @@ -73,6 +82,7 @@ The form and the request are written at different times by different people (or * Using `ifempty(parameters.x, undefined)` to hide empty values, then wondering why nobody can clear the field. * Output keys renamed in the projection but the interface still lists the old names. * Declaring an interface numeric when the provider returns an ID string, which breaks mapping downstream. +* Copying the keys of one test response into a collection whose keys each user defines (custom attributes, metadata), such as `"spec": [{ "name": "test_attr" }, { "name": "key1" }]`. The interface generator does this when it is given one sample, and the interface page says that generated code still needs review. Every user then sees those sample keys as mappable fields with misleading labels, while their own keys stay undeclared. Declare such a map with the documented unknown-structure shape, `{ "name": "metadata", "type": "collection", "label": "Metadata", "spec": [] }`, so whatever keys the provider returns can be mapped. Keys the provider itself defines stay declared; only the user-defined map gets the empty `spec`. ## Exceptions and applicability diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/labels-visibility.md b/skills/make-custom-apps/examples/current-knowledge/guides/labels-visibility.md index 909e95c..b205716 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/labels-visibility.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/labels-visibility.md @@ -18,6 +18,34 @@ A label can be wrong in a way that matters: * Two fields in the same form share a label, so the user cannot tell them apart (`CK-LABEL-UNIQUE`). * The label or description promises something the request does not do (for example "Delete permanently" on a call that archives). This one needs human review; no static rule covers it. +### Help text that contradicts its own field + +Users treat a help text as the field's contract, so it must describe the field it sits on. Two slips appear even in approved apps. Both show up when you read each help against its own `label`, `validate` and `default`: + +* **A range or special value that the validator rejects.** Help that says "From `0` to `5`. `0` turns retries off." next to `"validate": {"min": 1, "max": 5}` documents a value the form refuses. Make checks `validate` on a value typed into the field, so the user gets an error for the very value the help recommends. Take the range from the provider's documentation and make all three agree: widen `validate` when the provider accepts the value, otherwise correct the help. A default that the help states ("Defaults to `3`.") must match the field's `default`, or, for a field without one, the provider's documented behaviour for an empty value; a `default` should itself satisfy `validate`. A bound that rejects a value the provider documents as valid is a concrete finding when the provider page is cited, like a required flag that blocks a valid state. A mismatch in the help alone is a wording fix and advisory. +* **Help copied from a neighbouring field.** An "End date" whose help says "Start of the interval…", or a second key-value field that repeats the first field's sentence, misleads the user about what the value does. Look closely at paired fields (start/end, from/to, minimum/maximum). Identical help on a pair is correct when it describes what both share, such as a format ("Date in the format `DD-MM-YYYY`."). It is wrong when it names one side of the pair or another field's purpose. Fix only the wording; it changes neither validation nor the request. + +Help, `validate` and `default` that agree: + +~~~json +{ + "name": "retries", + "type": "uinteger", + "label": "Retries", + "validate": { "min": 0, "max": 5 }, + "default": 3, + "help": "Number of times a failed delivery is retried, from `0` to `5`. `0` turns retries off. Defaults to `3`." +} +~~~ + +### Delete, trash, archive and remove + +**Documented recommendation.** Make's [module descriptions](https://developers.make.com/custom-apps-documentation/best-practices/naming-conventions/modules/module-descriptions) page gives these operations their own patterns. "Delete a/an [item]" is described as "Deletes a/an [item]…", and "This action cannot be undone." is added only when the API documentation says so. "Move a/an [item] to trash" is described as "Moves a [item] to the trash." The [module labels](https://developers.make.com/custom-apps-documentation/best-practices/naming-conventions/modules/module-labels) page lists both "Delete a user from a list" and "Remove a user from a list", and asks for the third-party terminology users know where it differs from the suggested format. The label verb alone therefore does not tell the user whether the item can be recovered; the description must. + +**Inferred implementation pattern** (seen in approved apps). Name and describe the effect that the provider documents, not the HTTP verb: one provider's `DELETE` request moves a record to a recoverable trash, while another's removes it for good. Where the provider's own UI calls the recoverable operation "Delete", the familiar label can stay, but the description says what happens ("Deletes a file by moving it to the trash."). Claim permanence only with provider evidence ("Permanently deletes a file. This action cannot be undone."). Keep a permanent delete and a recoverable one apart: as separate, clearly named modules or Endpoints, or as an explicit choice inside one module. Where a recoverable alternative exists, mention it in the permanent one's description. Use the same wording in an Endpoint's description and context and in the ID field's help ("ID of the file to move to the trash."), because an AI agent chooses a tool largely from that text, and set the Endpoint's hints from the same documented effect (see [SDK Endpoints](../../../references/sdk-endpoints.md) for side effects and hints). + +The understated case is the more harmful mirror of the "Delete permanently" example above: "Archive" or "Move to trash" on a request that permanently deletes hides data loss from the user. Both directions are a label or description that promises something the request does not do. They are functional, not cosmetic, so trace them to the provider's documentation before you report them. A recoverable operation that keeps the provider's own word "Delete" and whose description says the item goes to the trash is not a defect. If that sentence is missing, add it as an advisory wording fix; do not rename the module. + ## Visibility: advanced fields, secrets, hidden fields **Documented behaviour.** Parameters can be marked `advanced`, which tucks them under an "Show advanced settings" toggle, and static parameters can be mappable or not. Text parameters offer `validate.min` and `validate.max` for length and `validate.pattern` (wrapped in `^$`); the validator keys are `min`/`max`, not `maxLength` (`maxLength` is a property of the provider's JSON schema, which is a different thing). diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/optional-endpoints.md b/skills/make-custom-apps/examples/current-knowledge/guides/optional-endpoints.md index 3829ba2..e752436 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/optional-endpoints.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/optional-endpoints.md @@ -15,7 +15,7 @@ The nearest *public* concept for a free-form call is the **universal module**. * ## Design pattern when you want one 1. Declare every input the Endpoint reads in the `inputParameters` **section**, and read each one in the request IML as `parameters.FIELD` (for example `{{parameters.recordId}}`). `inputParameters` names the definition section that declares inputs; it is not an expression root. The published SDK types establish only the section keys; the `parameters.FIELD` request namespace comes from this skill's [SDK Endpoints reference](../../../references/sdk-endpoints.md) and its maintainers' own check of the runtime namespace, so treat it as local evidence rather than a public-page statement. The checker's `CK-ENDPOINT-INPUT` rule inspects the request text for `parameters.*` reads of undeclared names and for the legacy `inputParameters.*` root. -2. Keep the URL relative to Base, so the same credentials and the same host apply. A fixed `baseUrl` with a path is not reached around by a user-supplied suffix. +2. Keep the URL relative to Base, so the same credentials and the same host apply. A fixed `baseUrl` alone does not keep a user-supplied path on that host, because a complete URL in the input is treated as absolute (as for module requests); if the Endpoint takes a free-form path, put a fixed prefix ending with `/` directly before it, as for the universal module ([universal-modules-and-scopes](universal-modules-and-scopes.md)). 3. Inherit Base headers (use the spread described in [headers-merge](headers-merge.md) if you add some). 4. An Endpoint may overlap what a module already does; there is no rule against it. Overlap is a design choice (different callers, a wire-contract input shape), and the Endpoint need not mirror a module's form. Reuse Base so the credentials and host rules stay in one place. @@ -31,6 +31,46 @@ The nearest *public* concept for a free-form call is the **universal module**. * The wrapper (`optional`, `endpoint`) belongs to this tree's synthetic fixtures. It is not a whole deployable Endpoint definition, and the example above only shows the declare-then-read relationship. Whether a free-form `path` input should exist at all is the arbitrary-call question the SDK reference treats separately. +### State repeat, reply and replace behaviour in the context + +The input and output schema does not tell a caller what a second identical call does, what the reply describes, or whether a list or role input adds to the current value or replaces it. Write these facts into the Endpoint's context, as part of the side effects the [SDK Endpoints reference](../../../references/sdk-endpoints.md) already asks it to document, and choose the annotations from the same provider evidence: + +* **Repeat call.** Say what a second identical call does. It may leave the record unchanged, return the existing record (a create-or-get by name), create a second record, or fail (a delete that answers "not found" because the record is already gone). `idempotentHint` describes effects, not replies: a repeat that creates a duplicate is not idempotent, while a repeat that has no further effect but returns an error can be. Say which case applies, so that a caller's retry does not read that error as a new failure. For a create that is not idempotent, say how to check before retrying (for example a search by a unique field), and name the upsert Endpoint by its exact name if the app has one. +* **What the reply reflects.** Say whether the reply shows the record as it was *before* the change (a delete whose reply still shows the record as active) or the new state. Replies with only identifiers or no body, and naming the Endpoint that reads the record back, are covered under **Write results** in the [SDK Endpoints reference](../../../references/sdk-endpoints.md). +* **Set, not add.** Say when an input replaces the current value instead of adding to it: a role that is set, or a list that becomes the complete set. Such an input removes what was there, so `destructiveHint` cannot be `false`, which the SDK type reserves for only additive updates. Repeat the warning in that input's `help`, where the caller reads it while filling in the value. Warn explicitly when the call can remove the connected account's own access: a lower role set on the connection's own user can make every later call on that resource fail with a permission error. + +~~~json +{ + "name": "role", + "type": "select", + "label": "Role", + "options": [ + { "label": "Owner", "value": "owner" }, + { "label": "Member", "value": "member" } + ], + "help": "Replaces the user's current role instead of adding to it, including an owner role. Setting a lower role on the connected account's own user removes its own access." +} +~~~ + +**Inferred implementation pattern.** Approved apps with Endpoints were seen stating these facts in their contexts and repeating the replace warning in the input help, and the parameter hints convention asks a hint to describe the result of a value. A missing note is context quality to improve, an advisory point. A note or annotation that contradicts the provider-evidenced behaviour is a finding to fix; its approval impact follows [Approval gating](../../../references/review-and-qa.md#2a-approval-gating). + +### Empty lists in Endpoint inputs + +**Documented behaviour.** The IML guide lets `ifempty` fall back only when the value is not defined, `null` or an empty string. An empty array is none of these, so `{{ifempty(parameters.fields, undefined)}}` still sends `[]`. To test a list, use `length()`, which returns the number of items in an array; the IML library also returns `0` for a missing value. + +**Inferred implementation pattern.** An Endpoint caller sends literal data, not scenario mappings: no erase pill and no scenario empty-value setting applies, and the caller tells omission and `[]` apart itself (under `fillDefaults: 'requiredOnly'` an optional input it leaves out stays absent). Verify that on the selected runner, then decide per list input from what the provider does with `[]`: + +* **A list that only shapes a read** (selected fields, sort keys), where the provider treats an absent list as its default but rejects `[]` or returns nothing useful for it. An empty list has no useful meaning there, so omit it with a length test and say so in the input's `help`. Do not apply this to a list of records to match, where omission would widen the read to every record. + +~~~json +"fields": "{{if(length(parameters.fields) > 0, parameters.fields, undefined)}}" +~~~ + +* **A list on an update.** Forward the list as given: an omitted list leaves the field unchanged, and `[]` clears it where the provider clears with `[]`. Do not use the length test here. If the mapping must still drop `[]` (the provider rejects it, or clears through another value), give the caller an explicit way to clear, such as a boolean input that sends the provider's clear value. Without one the Endpoint cannot clear that field, and the clearing operation becomes a no-op. +* **Say it where the caller reads it.** In the context and in the input's `help`, state what an omitted list does (for example the provider's default field set), what an empty list does, and how to clear. + +The length test on a read list is a narrow exception to the documented input-processing recommendation, which calls dropping empty arrays with `if` and `length` a bad practice because the user then cannot remove all values. That reason applies to updates, and there the recommendation stands. Test each list input with the value omitted, `[]` and one item through the actual request mapping, as the [SDK Endpoints reference](../../../references/sdk-endpoints.md) asks for empty containers. + ## Never required The rule here is deliberately one-directional. An Endpoint is optional by request scope. It is not a gate on approval unless the request explicitly requires endpoints (class (d) in [Approval gating](../../../references/review-and-qa.md#2a-approval-gating)), never something a review may demand because a provider has "more routes", and ordinary modules must never depend on one. `CK-ENDPOINT-OPTIONAL` enforces that a fixture marks it optional, and the catalog rejects a recipe that depends on the Endpoint recipe. diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/outputs-empty-values-updates.md b/skills/make-custom-apps/examples/current-knowledge/guides/outputs-empty-values-updates.md index cc23883..20d81c8 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/outputs-empty-values-updates.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/outputs-empty-values-updates.md @@ -16,6 +16,19 @@ Keep concepts distinct: the iterated item of a search, the wrapper object, and a **Precision.** A provider identifier too large for a JSON number can be rounded during parsing; switching the interface to text afterwards cannot recover digits. Use the documented response-parsing option, or have the provider send strings. Label derived units and rounding explicitly instead of replacing original values silently. +**Spread first, overrides after.** An output or a request body may combine the collection spread with computed keys (a `parseDate` on a timestamp, a parsed `result`, a formatted date). Write the spread first and the computed keys after it, or remove those keys from the spread with `omit`, as the documented input-processing example does. A key declared before the spread can be overwritten by a same-named key from the spread, and the user then maps the raw provider value instead of the converted one. The same holds in a helper: `return { ...response, result }` keeps the computed `result`, while `return { result, ...response }` lets a provider field named `result` replace it. The safe form, for a provider that documents `createdAt` as a Unix timestamp in seconds: + +```json +"output": { + "{{...}}": "{{body}}", + "createdAt": "{{parseDate(body.createdAt, 'X')}}" +} +``` + +Equally safe is `"createdAt"` first with `"{{...}}": "{{omit(body, 'createdAt')}}"` after it, because the spread then cannot carry a competing key. + +**One entry per name and level.** Each interface entry describes one key of the emitted bundle, so names must be unique at each level. Two entries with the same `name` at the same level describe one key twice. When their types differ (text in one, collection in the other), at most one of them can match a given run, and users cannot tell which item to map. This usually happens when the fields of several response variants (one per model, record type or operation) are merged into one static list. Declare each key once. Where the variants share a type, use it. Where the key is a collection in every variant but its fields differ, a collection with `spec: []` fits all of them. Where the type itself differs between variants, describe the key through a dynamic interface keyed on the option that selects the variant. + ## Empty values: omission, clearing and setting Model three intents separately: *leave unchanged*, *clear*, *set*. Legitimate `0`, `false`, empty strings and empty arrays can carry meaning, so cleanup based on truthiness changes data. @@ -53,6 +66,62 @@ Keep these layers separate and verify each independently: the permitted input (a Reference expectations for a synthetic contract (booleans, integer, text, array, nullable and optional controls) are in [reference-vectors.txt](../recipes/empty-values-contract/reference-vectors.txt). They are JSON data, not IML and not checker fixtures, and they are expectations rather than executed Make output. +### Recursive cleanup helpers: check every branch + +Recursive removal of empty values is a custom IML function that the app must define. `removeEmpty` is not a built-in IML function. Many apps include one, often adapted from the documented sample, and its branches are where data is silently lost. Before relying on such a helper, check and test each branch: + +* **Primitive array items.** An array branch that passes every element back through the helper loses scalars when the helper returns `undefined` for anything that is not an object. The documented sample does this as published, so `["a", "b"]` is sent as `[null, null]`, because `JSON.stringify` writes an `undefined` array element as `null` (standard JavaScript behaviour). Recurse only into objects, and pass strings, numbers and booleans through unchanged. +* **Dates and buffers.** Inside a function, values of `date` parameters and the results of `parseDate` are `Date` objects. A `Date` has no own keys, so an "empty object" test removes it. The documented sample keeps a date that is a property value with an `instanceof Date` check, but a date inside an array still goes through the object branch and comes out as `{}`. A `Buffer` has numeric keys, so a helper that recurses into it turns file data into a plain object of byte values. Treat both as leaves wherever they occur. +* **Truthiness filters.** `.filter(Boolean)` or `filter(([, v]) => v)` inside a helper drops `0`, `false` and `""` just as an inline `||` fallback would, but someone reading the module's communication cannot see it. Test for `null` and `undefined` explicitly. +* **Emptiness tested before cleaning.** If a collection is checked for keys before its children are cleaned, a collection whose only values were `null` still goes out as `{}`. The documented sample does this, so `{ "address": { "street": null } }` still sends `"address": {}`, which is the provider error the sample page sets out to avoid. Check emptiness on the cleaned result. +* **Clearing on updates.** Erase sends `null` for text and numbers and `[]` for arrays. A helper that strips `null` or empty arrays makes Erase do nothing in an update module. Keep those values in the helper used for updates, or apply the helper only to the fields whose provider rejects empty values. +* **Conditional spreads inside arrays.** Building parts as `[{ ...(text && { type: 'text', text }) }]` leaves `{}` in the array when the condition is false. Push only the parts that exist. +* **Nothing left.** When everything is removed, the documented sample returns `{}` and the version below returns `undefined`. Check that the call site (a whole `body`, or a `{{...}}` spread) and the provider accept that result, and test that case. + +A version that avoids the first four traps: + +```js +function removeEmpty(value) { + if (value === null || value === undefined) return undefined; + if (value instanceof Date || Buffer.isBuffer(value)) return value; // leaves + if (Array.isArray(value)) { + return value.map((item) => removeEmpty(item)).filter((item) => item !== undefined); + } + if (typeof value === 'object') { + const out = {}; + for (const [key, item] of Object.entries(value)) { + const cleaned = removeEmpty(item); + if (cleaned !== undefined) out[key] = cleaned; + } + return Object.keys(out).length > 0 ? out : undefined; // tested after cleaning + } + return value; // keeps 0, false and "" +} +``` + +It keeps empty arrays, so an array Erase still reaches the provider. It removes `null`, including `null` items and empty objects inside arrays, so it suits create requests, not updates that must clear text or numbers. For an update that must clear, keep `null`: return it unchanged instead of `undefined` in the first line, so an erased field still reaches the provider. Test it with an array of strings, an array of objects, a `Date` (also inside an array), a `Buffer`, `0`, `false`, `""`, a collection that holds only `null` values, and an input where everything is empty. An expected value that contains `undefined` or `null` elements records the defect instead of catching it. + +### Whole-parameter spreads: complete the omit list + +`"{{...}}": "{{omit(parameters, ...)}}"` sends every parameter that has a value and that the list does not name. The input-processing page gives the reasons to omit a parameter: it is used somewhere else, it should not be sent at all (technical parameters such as selects), or it needs special handling. In each spread, name: + +* identifiers already used in the URL path; +* the module's own result limit (read by `response.limit`) and any page-size or pagination input; +* mode and source selectors, parent selectors that exist only to feed an RPC, and other form-only controls; +* parameters that are already mapped under another key, or that are transformed explicitly (for example a date passed through `formatDate`). + +When a module has several conditional requests, each request has its own spread and needs its own complete list. Compare each list with the parameters that are visible in that branch. An unknown query or body key can make the provider reject the request, or can quietly change a filter. + +### Optional collections: send them only when filled + +On Apps platform version 2, a collection whose fields the user leaves empty still reaches the request as `{}`, while Erase on one of its fields sends the collection with that field set to `null`. Where the provider rejects or misreads an empty object, guard that one collection instead of cleaning the whole body: + +```json +"settings": "{{if(length(keys(parameters.settings)) > 0, parameters.settings, undefined)}}" +``` + +The guard omits only an untouched collection. A collection with an erased field still has a key, so it is sent and clearing keeps working. Where a parent holds several optional groups, guard each sub-collection. In a read-and-merge update, do not use the same test to choose between the user's collection and the fetched one: a partly filled collection would then replace every stored field the user left empty, which is the shallow-merge problem described under updates, and a note in the help does not make that replacement safe. Do not reuse the guard for arrays. The input-processing page lists `if(length(parameters.tags) > 0, parameters.tags, undefined)` as bad practice, because it makes it impossible to send an empty array, which is the Erase value for arrays. + ## Updates: partial or full replacement Decide from the provider's contract, not the HTTP verb: some APIs support partial behaviour through PUT, and some PATCH calls still replace nested collections. @@ -61,6 +130,19 @@ Decide from the provider's contract, not the HTTP verb: some APIs support partia * If the provider documents **partial** updates, an extra read is unnecessary cost and adds concurrency and permission risk. * A warning in the description does not make a destructive replacement safe. * A read followed by one write is the valid shape of that merge. It is different from several independent writes in one module, which the [batch-actions best practices](https://developers.make.com/custom-apps-documentation/best-practices/modules/batch-actions) say cannot report partial success and recommend splitting into separate modules. Classify requests by side effects, not HTTP verb, and see [requests-files-multistep](requests-files-multistep.md) for the exceptions and for what a request array does and does not guarantee. +* **Defaults on update inputs.** A `default` pre-fills the field in every newly added module. An update module therefore sends that value whenever the user does not clear it, and the stored value is reset even though the user only meant to change another field (for example a status select preset to "open", or an archive boolean preset to true). Leaving a value unchanged relies on the field being empty, so optional inputs of an update module normally have no `default`. Keep defaults on create modules, where they mirror the provider's own default. A control that only steers the module, such as a "Replace the list" switch that defaults to No, may keep a default that means "leave unchanged". Check booleans too: an untouched boolean without a default sends nothing, but `default: true` or `default: false` sends that value. +* **Array fields that replace the stored list.** When the provider replaces an array on update (tags, lines, media, recipients), say so in the field's help. Where the provider keeps a field that the request omits, leaving the field empty keeps the current list. Any mapped value replaces the whole list. Erase sends an empty array, which removes all items where the provider accepts one. To add one item, the user first gets the record and then maps the existing items together with the new one. Mirror the provider's item limit in `validate.maxItems`; the `50` below stands for that documented limit. Write the help in the documented hint order: expected input, result, additional information, then what happens if left empty. Without this help, users who map one new item silently delete the rest. + + ```json + { + "name": "tags", + "type": "array", + "label": "Tags", + "spec": { "type": "text", "label": "Tag" }, + "help": "Tags to set on the record. Mapped tags replace all existing tags. To add a tag, map the current tags from a Get module together with the new one. If left empty, the current tags are kept.", + "validate": { "maxItems": 50 } + } + ``` ## Dynamic fields and metadata diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/pagination-and-trigger-state.md b/skills/make-custom-apps/examples/current-knowledge/guides/pagination-and-trigger-state.md index afd6b54..b2ef9de 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/pagination-and-trigger-state.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/pagination-and-trigger-state.md @@ -24,6 +24,8 @@ Add an explicit condition when the provider repeats its last page, returns empty Keep the iterated resource, selected fields, filters and response shape the same on later pages. Client-side filtering should be tested with eligible records on later pages; do not assume an undocumented order between filtering and the limit. +Offset positions are not stable identities. When a record is created or deleted between two page requests, every later record shifts: in a newest-first list an insert pushes the last record of one page onto the next, so it is fetched twice, and a delete pulls a record into the range already fetched, so it is never fetched. A polling trigger may never return to that record, because it is older than the date saved after the run. Prefer a cursor, a next link or a filter bound by the saved date or ID when the provider offers one. With offsets, request a stable sort with a unique tie-breaker (date, then ID), and add a record created or deleted between two page requests to the edge tests. + ### Test the edges Initial page, one continuation, final page, empty result, and a small total limit (smaller than one page). Use distinguishable test records and a tiny page size to reveal overlap or skipped records. The pagination debugging page describes how to inspect each request. @@ -41,6 +43,42 @@ Initial page, one continuation, final page, empty result, and a small total limi * Equal timestamps need an ID tie-breaker in the design. * Updated, deleted and late-arriving records are separate cases; decide whether the trigger watches creation or modification and say so in the module description. * Declared order must describe the order actually requested. A mismatch between the request's direction and `order` is a genuine inconsistency; a missing manual state assignment is not. +* A request that sends no sort or direction parameter still declares an `order`; it then describes the provider's *default* order. Make uses the declared order to decide whether more pages are needed and how to sort what it emits, so that default has to be real. The trigger guidance accepts results that are "sorted or defaulted in descending order", so a missing sort parameter is not a defect when the provider documents a newest-first default. It is not proof of consistency either: a comparison of declared and requested direction has nothing to compare here, so check the provider documentation or a recorded response with several items. When the provider offers a sort parameter but documents no default order, send the sort explicitly in the declared direction; when neither is possible, declare `unordered`. + +**Inferred implementation pattern: request the fields the trigger reads.** `trigger.id` must return each item's ID and, for a date trigger, `trigger.date` its date. When the module lets the user choose which fields the provider returns (a field list, `$select`, attributes), add the fields the trigger reads to a non-empty selection even if the user did not pick them; otherwise the provider leaves them out, the ID or date evaluates empty, and the item cannot be compared with the saved state. When the selection is empty and the provider then returns its default field set, confirm that set contains them. For a date trigger, use one field for the provider sort, any date filter, the forced field and `trigger.date`, so that the declared order describes the field Make compares; when the user chooses what to watch (for example created or updated), derive all of them from that one parameter. + +```json +{ + "qs": { + "fields": "{{if(length(parameters.fields), join(distinct(add(parameters.fields, 'id', parameters.watchBy)), ','), undefined)}}", + "sort": "-{{parameters.watchBy}}" + }, + "response": { + "trigger": { + "type": "date", + "order": "desc", + "id": "{{item.id}}", + "date": "{{get(item, parameters.watchBy)}}" + } + } +} +``` + +**Documented recommendation: bound the request with the saved state.** Where the provider can return only records after a date or numeric ID, pass `data.lastDate` or `data.lastId` into that filter instead of asking the user for fixed dates; an interval API takes `data.lastDate` as the start and `{{now}}` as the end. Still request newest first where the provider allows it. Where it does not, the bound is what keeps an ascending or unordered trigger workable within the 3200-record limit, because it reduces the records fetched. In a request, `{{data.lastDate}}` is sent as ISO 8601 text in UTC with milliseconds (`1970-01-01T00:00:00.001Z`), which the trigger page does not state, so check a run's request log; convert it only when the provider's filter expects another unit or precision, for example Unix seconds with `formatDate(data.lastDate, 'X')`. Prefer an inclusive bound (`since`, `gte`): the trigger returns only unprocessed items (it compares each item with the saved date and ID), so the boundary record is not emitted twice, while an exclusive bound at second or day precision can lose records that share the boundary timestamp. + +**Documented behaviour: there is no empty start date.** The **Choose where to start** options all send a date in `data.lastDate`: the current date (From now on), the given date (Since specific date), the chosen item's date (Choose manually) or the default `1970-01-01` (All). A trigger run with no saved date receives the Unix epoch start `1970-01-01T00:00:00.001Z` (not stated on the trigger page; confirm in a run), also when the trigger has no epoch. On an `id` trigger `data.lastDate` stays at that start across runs (not stated on the trigger page; confirm in a run), so bound an `id` trigger by `data.lastId`. A truthiness test such as `{{if(data.lastDate, ..., fallback)}}` is therefore not a first-run test, and a fallback window (for example "the last 24 hours") never runs in trigger executions; the user's start choice, or the epoch start when the trigger has no epoch, is the first-run policy. When the provider rejects so old a bound, test for the epoch start explicitly and omit the filter, which still means "all records". Compare the year, not an exact value: formatted in a zone west of UTC, the start falls in 1969. For a provider whose filter takes Unix seconds: + +```json +{ + "qs": { + "updated_since": "{{if(formatDate(data.lastDate, 'YYYY') <= '1970', undefined, formatDate(data.lastDate, 'X'))}}", + "sort": "-updated_at" + }, + "response": { + "trigger": { "type": "date", "order": "desc", "id": "{{item.id}}", "date": "{{item.updated_at}}" } + } +} +``` ## Rationale @@ -56,6 +94,10 @@ Pagination and trigger state both trade completeness against budget. Make's defa * Using ascending order against a busy provider because it is the provider's default. * Reporting missing trigger state because no assignment of previous-run values appears. * Changing a pagination field selection between pages. +* Letting a user-selected field list leave out the field that `trigger.id`, `trigger.date` or the provider sort reads. +* Using `{{if(data.lastDate, ...)}}` as a first-run test, or overriding the user's **Choose where to start** choice with a fallback window; in a trigger run `data.lastDate` always carries a date, the Unix epoch start when nothing was saved or All was chosen. +* Accepting or rejecting a trigger that sends no sort parameter without checking the provider's documented default order. +* Offset paging over a list that changes during the run without a stable sort and a test that creates or deletes a record between pages. ## Exceptions and applicability @@ -69,6 +111,9 @@ Pagination and trigger state both trade completeness against budget. Make's defa * Collection-body deep merging for eligible request types and replacement of array values: **author-observed runtime behaviour**, contrary to the Pagination page's body-replacement wording; not established by that published page or by static checks. * Newest-first ordering and the lost-window reason: **documented recommendation**. * Provider cursor semantics, tie handling and exhaustion are provider facts; only execution against the provider and fresh pagination evidence show them. +* Bounding the request with `data.lastDate` or `data.lastId` (with `{{now}}` as an interval end), the dates sent by the **Choose where to start** options including `1970-01-01` for All, the trigger returning only unprocessed items, and acceptance of a documented descending default: **documented recommendation** and **documented behaviour** (trigger best practices and trigger pages). +* The Unix epoch start in `data.lastDate` when no date was saved, its ISO 8601 UTC serialisation in a request, and `data.lastDate` staying at that start on an `id` trigger: **not documented**: not stated on the trigger page, so confirm them in a run's request log before relying on them. +* Requesting the fields the trigger reads, one field for sort, filter and `trigger.date`, the year test for the epoch start, and offset shifts under inserts and deletes: **inferred implementation pattern** from the documented trigger and pagination semantics; whether a provider's offsets shift, and its default order, are provider facts to check against its documentation or a recorded run. ## Sources diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/requests-files-multistep.md b/skills/make-custom-apps/examples/current-knowledge/guides/requests-files-multistep.md index 17fad24..bb3499d 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/requests-files-multistep.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/requests-files-multistep.md @@ -8,6 +8,32 @@ Most modules are one request. Some are not: a file moves as bytes rather than te Map every path, query, header and body field to its input or execution-context source. Verify requiredness, encoding, content type, data type and nested shape. Keep shared authentication and stable defaults in Base ([headers-merge](headers-merge.md)) and see how the operation overrides them. Use `qs` and `headers` as flat collections; arrays in `qs` become repeated keys. Sanitise sensitive locations, including token exchanges and credentials outside headers ([auth-context](auth-context.md)). For signed requests, the signature inputs must match the transmitted method, URL encoding, headers and payload bytes exactly. +### Multipart bodies you build yourself + +**Documented behaviour.** With the request `type` `multipart/form-data`, Make builds the body and its boundary itself. An array of `{ "name", "value" }` items keeps the field order. The other request types are `json`, `urlencoded`, `text` (or `string` or `raw`) and `binary`. Make sets the `Content-Type` header automatically only for `json`, `urlencoded` and `multipart/form-data`. + +Some providers need a multipart flavour that Make does not encode, such as a `multipart/mixed` batch that bundles many sub-requests into one call or `multipart/related`, or an exact byte layout. For these, build the body in a custom function and send it as `text`, or as `binary` with a Buffer when the parts contain raw bytes. Then: + +* Generate the boundary once, in the request's `temp` or as one constant that the function shares, and use that same value in the `Content-Type` header and in the body. Values generated separately never match. +* Strip quotes and line breaks from any value written into a part header (a file name, for example), so that the value cannot end the header line or add part headers. +* Read the answer with `response.type: "text"` and parse it into items in a function. Every part carries its own status, so an HTTP 200 for the batch does not mean that every part succeeded ([errors-and-rate-limits](errors-and-rate-limits.md)). +* Keep each call within the provider's per-batch maximum, walk longer lists in slices with a bounded `repeat`, and append the parsed results ([How `temp` merges arrays and objects](#how-temp-merges-arrays-and-objects)). + +```json +{ + "url": "/batch", + "method": "POST", + "type": "text", + "temp": { "boundary": "batch_{{uuid}}" }, + "headers": { "content-type": "multipart/mixed; boundary={{temp.boundary}}" }, + "body": "{{buildBatchBody(temp.pendingIds, temp.boundary)}}", + "response": { + "type": "text", + "temp": { "results": "{{merge(temp.results || emptyarray, parseBatchBody(body))}}" } + } +} +``` + ## Files: bytes, names and metadata **Documented behaviour.** @@ -30,6 +56,63 @@ Map every path, query, header and body field to its input or execution-context s Text conversion is not a harmless default for binary content. A file-like URL or a MIME header does not prove the response was decoded as binary; the response `type` decides. Large files are subject to the same call timeout as any request. +**File names for downloaded files.** Users see the name in every later module, so derive it deliberately and never output an empty one. Try these sources in order: the response's `Content-Disposition` header, then the last path segment of the download URL without its query (decoded), then a default built from the record identifier and the extension of the real content. In `Content-Disposition`, the extended form `filename*=UTF-8''…` is percent-encoded and takes precedence over `filename=`. A quoted name can contain `=` and `;`, so splitting the header on `=` and keeping the last piece cuts real names short. A small custom function handles all of these forms: + +```js +function fileNameFromDisposition(header, fallback) { + const value = String(header || ''); + const extended = /filename\*\s*=\s*"?[^']*'[^']*'([^;\s"]+)/i.exec(value); + if (extended) { + try { return decodeURIComponent(extended[1]); } catch (e) { /* use the plain form */ } + } + const plain = /filename\s*=\s*(?:"([^"]*)"|([^;]+))/i.exec(value); + const name = plain ? (plain[1] !== undefined ? plain[1] : plain[2]).trim() : ''; + return name || fallback; +} +``` + +```json +"output": { + "fileName": "{{ifempty(parameters.fileName, fileNameFromDisposition(headers.`content-disposition`, 'document-' + parameters.id + '.pdf'))}}", + "data": "{{body}}" +} +``` + +The `.pdf` default fits an endpoint that always returns PDF. Where users need to choose the name, offer an optional `filename` input and let it win. Make the extension match the real content: take it from the response `Content-Type`, from the format the user requested, or from the type the provider declares, not from a fixed literal such as `output.jpg`. An IML-only expression that cannot parse every form must still fall back to a default when the header is missing. + +**Base64 file content inside a JSON response.** Some providers return a generated file as a base64 string inside JSON instead of as a binary body. Passing that string on gives the next module a text field, not a file it can map. Convert the string to binary with the documented `toBinary(value, 'base64')`, either in the mapping or in a custom function as `iml.toBinary(value, 'base64')` (or `Buffer.from(value, 'base64')`). Then output it as the name and data pair with the `filename`/`buffer` types and `file:name`/`file:data` semantics described above. + +```json +"response": { + "output": { + "fileName": "{{ifempty(parameters.fileName, 'document-' + body.id + '.pdf')}}", + "data": "{{toBinary(body.content, 'base64')}}" + } +} +``` + +The `.pdf` default fits an endpoint that always returns PDF. When the response holds several files, output one name and data pair per file, each with a distinct name (`image-1.png`, `image-2.png`), and take the extension from the real format. When the bytes are optional, for example behind an "include file content" choice, leave `data` undefined unless the user asked for it. Do not fetch or decode them anyway: each extra file can cost a request and memory. + +**Files the provider wants as base64 inside JSON.** Some providers document a base64 field, or a `data:` URI, instead of multipart or raw bytes. Even then, keep the user-facing input a file: a `buffer` with `file:data` and a name with `file:name`. Convert it when the request is built, with `buffer.toString('base64')` in a custom function (Buffer is available there) or, as approved apps also do, `base64()` on the buffer in IML. Guard the conversion so that an empty optional file sends nothing: a file collection the user left empty must not be sent as `{}` or as an empty string, because the provider then rejects an image that was simply not set. + +A `data:` URI needs a real media type: `data:;base64,`. Take the MIME type from a type the provider declares, from the file signature, or from a verified extension map (`jpg` and `jpeg` both map to `image/jpeg`). Never build it from the raw file name or extension, which produces `image/photo.png` or `image/jpg`. The documented `mime()` function, called in a custom function as `iml.mime(name)`, returns the type for a known extension and nothing for an unknown one. When the type is unsupported, stop with a clear error instead of sending a guess. Send only metadata you actually know: an invented `size: 0` or content type can be rejected, or can mislead the provider. + +```js +function toDataUri(fileName, data) { + const types = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', pdf: 'application/pdf' }; + const name = String(fileName || ''); + const mime = name.includes('.') ? types[name.split('.').pop().toLowerCase()] : undefined; + if (!mime) throw new Error(`Unsupported file type: ${name || '(no file name)'}`); + return `data:${mime};base64,${Buffer.from(data).toString('base64')}`; +} +``` + +```json +"image": "{{if(parameters.image.data, toDataUri(parameters.image.fileName, parameters.image.data), undefined)}}" +``` + +Test such a helper with a realistic name, a name without an extension and an upper-case extension. A unit test that only asserts the string the helper already produces (`data:image/test.png;base64,…`) locks the defect in instead of catching it. + ## Several requests in one module **Documented behaviour.** @@ -46,6 +129,75 @@ Text conversion is not a harmless default for binary content. A file-like URL or ] ``` +### A follow-up request to a URL the provider returned + +Download and upload flows often end with a request to a URL that an earlier response supplied: a temporary download link, a signed upload URL, a CDN address, or a link relative to the API host. A relative link is appended to the Base URL, so check that the joined URL does not repeat a path segment such as the version. + +**Documented behaviour.** Base is inherited by every module and RPC, and a complete `url` takes the place of the Base URL only. The rest of Base still applies to that request: its headers, including the credential, its query string and body defaults, its `response` handling and its log settings. A module `headers` collection merges with Base by name, so an empty collection (`"headers": {}`) removes nothing; a same-named entry replaces the Base value, and a whole-expression `headers` value replaces all Base headers ([headers-merge](headers-merge.md)). + +**Design rules.** + +* Decide the credential for that step from the provider's documentation. If the documentation says the returned URL expects the API credential (some upload URLs do), keep it and say so. Otherwise do not send the API credential to a host the provider does not document for it, such as a storage or CDN host, or to a URL that already carries a signature in its query. Sending it there hands the credential to another host, and signed-URL hosts can reject a request that carries a second authorization. Keep any header the signed URL was issued for, and leave the steps that call the API as they are. +* Remove the credential on purpose: set each credential entry to `"{{undefined}}"` by name in that step (a Base header, or a Base query parameter; see [headers-merge](headers-merge.md#dropping-one-inherited-header-in-one-request)), or give the step a whole-expression `headers` value that returns only what the step needs, for example the upload's content type. Check a test run's request log to see what the step actually sent. Treat any other form, such as a blank `""` or `"headers": null`, as unproven until that log shows the credential is gone. A credential that reaches another host is a security finding, not a masking issue ([approval gating](../../../references/review-and-qa.md#2a-approval-gating)): fix it on that step. The provider chose the host, so it is never a reason to reject. +* Validate the lookup on the request that returns the URL (`response.valid` with a message). An empty value does not fail on its own: it is treated as a relative URL, so the step calls the Base URL itself, with the credential. +* Give the step its own `response.error` message, and parse error answers per status ([requests and responses](../../../references/requests-and-responses.md)). The inherited Base `response` handling expects the API's body. A storage host answers in its own format, often XML, so an inherited message renders as a bare status code. Also check that an inherited `valid` condition or per-status error entry still fits this step: a per-status entry takes precedence over the step's generic message. +* Pass the URL exactly as it was returned. No `encodeUrl` setting fits every returned URL: with `false`, Make decodes the percent-encoded query string, which can break a signature; with the default `true`, Make encodes special characters again, `%` included, so a path the provider already percent-encoded (`my%20file.pdf`) can be sent double-encoded. Keep the default unless the test below shows a double-encoded path in the request log. Test with a file name that contains a space or a non-ASCII character. +* Repeat on each request any module-level header it needs, such as a tenant or scope header. A request in the array gets Base plus its own settings, not the headers of the request before it. + +```json +[ + { + "url": "/files/{{parameters.fileId}}/download-link", + "method": "POST", + "response": { + "valid": { "condition": "{{body.url}}", "message": "The file has no download link." }, + "temp": { "downloadUrl": "{{body.url}}", "fileName": "{{body.name}}" } + } + }, + { + "url": "{{temp.downloadUrl}}", + "method": "GET", + "headers": { "authorization": "{{undefined}}" }, + "response": { + "type": "binary", + "error": { "message": "[{{statusCode}}] The file host refused the download link. It may have expired." }, + "output": { "fileName": "{{temp.fileName}}", "data": "{{body}}" } + } + } +] +``` + +Approved apps were seen following both branches: some keep the credential because the provider requires it at the upload URL, and others clear it for a storage or CDN host. + +### How `temp` merges arrays and objects + +**Documented behaviour.** Values written to `temp` are merged into what is already there, not overwritten. + +**Not stated on the public page; confirm it with a test run.** The same merge applies across requests, repeat iterations and pagination within one execution. Objects merge key by key, so a key that a later write omits keeps its old value, and a shrinking "still pending" map never empties. Arrays merge position by position: when a shorter array is written, the old elements beyond its end survive, and each element object keeps any properties the new element lacks. An `undefined` value or an empty array leaves the old value in place. A `temp` array is therefore safe while it only grows: append with `add()` or `merge()`, and use `distinct()` by id where needed. Writing a filtered, re-sorted or retried subset back to the same key is not safe. It moves records onto the wrong positions, leaves stale elements behind, and can carry one record's properties, such as an old error or a field, into another record. A happy-path test does not show this. + +**Design rules.** + +* Accumulate under one key, append-only. +* Write a filtered, re-ordered or retried result to a key that has not held a longer array in this execution, or compute it in the final step's `output`, and read the final shape from there. +* Do not rely on `undefined` or `[]` to clear a key. Store an explicit end value for a loop control instead, for example `"next": "{{ifempty(body.next_cursor, false)}}"`: a cursor that resolves to nothing leaves the previous one in place, and a loop that stops on `temp.next` keeps requesting it. +* Test a chain that drops or retries an item in the middle of a list, and check that every output record still carries only its own data. + +```json +[ + { + "url": "/items/batch", + "method": "POST", + "body": { "ids": "{{parameters.ids}}" }, + "response": { "temp": { "results": "{{distinct(merge(temp.results || emptyarray, body.results), 'id')}}" } } + }, + { + "response": { "output": "{{removeFailed(temp.results)}}" } + } +] +``` + +The unsafe variant writes `"results": "{{removeFailed(temp.results)}}"` back into `temp` in a later request. + ## Independent writes in one module **Documented behaviour.** The [batch-actions best practices](https://developers.make.com/custom-apps-documentation/best-practices/modules/batch-actions) say that a module cannot report partial success: it either succeeds or fails as a whole, so a module that performs several independent changes can fail after the first one has already been applied. The recommendation is separate modules, one change each, so that every success and every failure is visible and can be handled on its own. The [multiple-requests page](https://developers.make.com/custom-apps-documentation/component-blocks/api/multiple-requests) defines what a request array does: the requests run in sequence and the last request's output is the module's output. It does not promise a transaction, a rollback or an automatic retry, and an HTTP error cannot be reclassified as success so that a later request can continue as recovery. @@ -80,6 +232,39 @@ Separate three things: *starting* a job, *observing* progress, and *retrieving* An export example, in prose: step one creates the export and stores its identifier in `temp`; step two polls the status with a bounded repeat until a terminal status; step three downloads the finished file as a binary response. A failed terminal status is an error, and a still-pending state at the limit is reported as such. +### Calling the provider once per element of a list + +When the provider has no bulk endpoint, a module can request each element of a list that an earlier request returned, for example one content call per attachment or one output call per task. + +```json +[ + { + "url": "/messages/{{parameters.messageId}}", + "method": "GET", + "response": { "temp": { "parts": "{{body.attachments}}" } } + }, + { + "condition": "{{parameters.includeContent && length(temp.parts) > 0}}", + "temp": { "partIndex": "{{ifempty(temp.partIndex, 1)}}", "includeContent": "{{parameters.includeContent}}" }, + "url": "/messages/{{parameters.messageId}}/attachments/{{get(temp.parts, temp.partIndex + '.id')}}", + "method": "GET", + "response": { + "temp": { + "contents": "{{add(temp.contents || emptyarray, body)}}", + "partIndex": "{{temp.partIndex + 1}}" + } + }, + "repeat": { "condition": "{{temp.includeContent && temp.partIndex <= length(temp.parts)}}", "delay": 200, "limit": 50 } + }, + { "response": { "output": { "attachments": "{{temp.parts}}", "contents": "{{temp.contents}}" } } } +] +``` + +* IML arrays are one-based, so start the position at 1 in the request's own `temp` and read the element with `get(list, position + '.field')`. Advance the position in `response.temp`, after the request has used it. The request-level `temp` runs before every repetition: if a position that starts at 1 is advanced there, the loop skips the first element and reads past the end. +* Append the results ([How `temp` merges arrays and objects](#how-temp-merges-arrays-and-objects)). Stop with `position <= length(list)`, and gate the whole step with a `condition` so that an empty list or an unset opt-in sends no request. Put the same gate into `repeat.condition`, read from `temp`, because a repeat condition can read only `temp` (the request's own `temp` copies the opt-in there before every pass): a pass that the request's `condition` skips does not advance the position, so without it the step can keep repeating until the limit. +* `temp` keys live for the whole execution, so give each loop its own position key; otherwise a second loop starts where the first one stopped. +* Each element costs one request against the call timeout and the provider's rate limit. Cap the list, set a literal `limit` at least that large, and add a `delay` where the provider needs one. A loop that reaches its limit with elements left has not finished the list. When the per-element data is large or not always needed, make fetching it opt-in. + ## Rationale Multi-step and binary flows add failure modes the user cannot see. Making each step's input, state and bound explicit lets a reviewer verify the chain without running it and lets the author reason about duplicates, timeouts and partial completion. @@ -96,6 +281,16 @@ Multi-step and binary flows add failure modes the user cannot see. Making each s * Using a request array where plain pagination fits. * Chaining independent writes in one module and assuming a later request can undo an earlier one; nothing here is transactional. * Classifying a request as a read or a write from its HTTP verb alone. +* Assuming that an absolute URL or an empty `headers` collection drops the Base credential, and so sending the API credential to a storage or CDN host that a response returned. +* Following a returned URL without checking that it is present; an empty value calls the Base URL. +* Setting `encodeUrl: false` on a signed URL whose query is already percent-encoded. +* Outputting an empty file name, or deriving it by splitting `Content-Disposition` on `=`. +* Passing base64 file content on as text instead of converting it to a buffer. +* Building a `data:` URI media type from a file name or extension, or sending invented file metadata. +* Writing a filtered, re-sorted or shorter array back to the same `temp` key. +* Starting a per-element loop at 0, or advancing its position before the request has used it. +* Gating a repeated request with `condition` but not its `repeat.condition`, so a skipped pass repeats until the limit. +* Generating a multipart boundary separately for the header and for the body. ## Exceptions and applicability @@ -109,6 +304,9 @@ Multi-step and binary flows add failure modes the user cannot see. Making each s * Partial success being unsupported and separate modules being recommended: **documented best practice**. The side-effect classification and the treatment of each sequence are an authoring judgment built on it. No static rule here evaluates it, and nothing in this tree shows how a particular provider or Make execution behaves after a partial failure. * Job states, idempotency and file protocols: **provider contract**; verify against the provider. * The static checker does not examine files, multipart bodies or request arrays. +* Absolute URLs replacing only the Base URL, a relative URL being appended to the Base URL, Base inheritance, header merging by name and whole-expression replacement, per-status error entries taking precedence over the generic message, `encodeUrl: false` decoding the query string, `toBinary` with base64 and `mime()`, request and response types, and `temp` merging rather than overwriting: **documented behaviour**. +* `temp` arrays merging position by position, `undefined` and `[]` not clearing a key, a request's own `temp` running before every repetition, and a request in an array not receiving the headers of the request before it: **not documented**: not stated on a public page. Confirm it with a test run when a decision depends on it. +* Whether a returned URL expects the API credential, multipart batch formats, per-part statuses and `Content-Disposition` forms: **provider contract** and HTTP standards; verify them against the provider. ## Sources diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/role-application-examples.md b/skills/make-custom-apps/examples/current-knowledge/guides/role-application-examples.md index 75f304a..cebadae 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/role-application-examples.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/role-application-examples.md @@ -46,9 +46,9 @@ Finding statements: * Output converts `createdAt` but the interface still says `text`: matching declaration missing. * Output is only `{{body}}` with `createdAt` documented as non-ISO: conversion needed (documented requirement). * A field in the response but not in the interface: declaration gap, not data loss. Output that builds a new object omitting a required field: demonstrable loss. -* Raw canonical ISO datetime text from HTTP JSON, output `{{body}}`, interface `date`, no traced conversion: record an explicit-conversion recommendation and unproven Date provenance. Not an automatic blocker, unambiguous violation or runtime failure: the focused output page recommends parsing, while the official full polling example emits an ISO field directly with a `date` interface. ISO spelling or the interface does not prove a Date conversion. +* Raw canonical ISO datetime text from HTTP JSON, output `{{body}}`, interface `date`, no traced conversion: the value stays text, so parse it with the provider's format. Not a runtime failure, but a finding: the focused output page recommends parsing and marketplace review treats the unparsed value as Required; the official full polling example that emits an ISO field directly with a `date` interface is no exemption. ISO spelling or the interface does not prove a Date conversion. * Traced value already an actual Date (earlier valid conversion, identity pass-through): no redundant-conversion finding; do not require a second parse. -* Not a finding: no `parseDate` token for `dueDay`, `localTime` or `sequence` (documented exceptions); verify meaning, zone and matching `date` interface for every emitted datetime. +* Not a finding: no `parseDate` token for `dueDay` or `sequence` (documented exceptions); verify meaning, zone and matching `date` interface for every emitted datetime. `localTime` is `uncertain` while its zone is undocumented, not dismissed. Cursor control: a polling trigger may map `trigger.date` directly when the provider field is established as the documented comparable ISO representation for that cursor pattern; a value that merely looks ISO-shaped is not enough. That is a cursor pattern and says nothing about output typing. A documented epoch cursor does need interpretation in the stated unit. @@ -60,7 +60,7 @@ Provider documentation requires an `X-Api-Version` header on some calls. The RES { "mappable_parameters": [ { "name": "url", "type": "text", "required": true, "label": "URL", - "help": "Relative path only, starting with `/`, for example `/v1/items`. The fixed provider address is added for you; do not enter a full URL." }, + "help": "Enter a path relative to `https://api.provider.example.com/api`. For example: `/v1/items`. Do not enter a full URL." }, { "name": "method", "type": "select", "required": true, "default": "GET", "options": [ { "label": "GET", "value": "GET" }, @@ -73,7 +73,7 @@ Provider documentation requires an `X-Api-Version` header on some calls. The RES "spec": [ { "name": "key", "type": "text" }, { "name": "value", "type": "text" } ] } ], "communication": { - "url": "https://api.provider.example.com/api/v1{{parameters.url}}", + "url": "https://api.provider.example.com/api/{{parameters.url}}", "method": "{{parameters.method}}", "headers": { "{{...}}": "{{toCollection(parameters.headers, 'key', 'value')}}" @@ -82,7 +82,7 @@ Provider documentation requires an `X-Api-Version` header on some calls. The RES } ``` -Check 0, destination boundary: the displayed `url` puts a literal provider prefix that includes a fixed path (`https://api.provider.example.com/api/v1`) before the interpolated input, and the input help asks for a relative path starting with `/`. The literal must include the slash and path before any untrusted input. A prefix of only scheme and host (`https://api.provider.example.com{{parameters.url}}`) is not enough: by URL grammar the authority has not necessarily ended, so an input such as `@other.invalid/` is read as userinfo and the hostname becomes `other.invalid`. With the fixed `/api/v1` literal, the authority has already ended, so caller input stays in the path; `@` and `//` cannot override the host. An unrestricted `"url": "{{parameters.url}}"` is the unsafe form: the platform's request handling treats a complete URL as absolute and does not apply Base to it, so a user-typed absolute URL could send the connection's credentials to another server (hardening: add the fixed prefix and approve with adjustments, never reject), which the [universal module page](https://developers.make.com/custom-apps-documentation/app-components/modules/universal-module) says relative-only input exists to prevent. A fixed Base `baseUrl` alone does not close this. This is teaching guidance on a synthetic fixture, not a complete validator, and it does not claim live execution or that any provider or Make runtime was exercised. Whether the Base-auth header collides is a separate unknown (Check 2). +Check 0, destination boundary: the displayed `url` puts a literal provider prefix that includes a fixed path (`https://api.provider.example.com/api/`) before the interpolated input, and the input help asks for a relative path starting with `/` and the version (the resulting double slash is removed automatically and is not a defect). The literal must close the host with `/` before any untrusted input. A prefix of only scheme and host (`https://api.provider.example.com{{parameters.url}}`) is not enough: by URL grammar the authority has not necessarily ended, so an input such as `@other.invalid/` is read as userinfo and the hostname becomes `other.invalid`. With the fixed `/api/` literal, the authority has already ended, so caller input stays in the path; `@` and `//` cannot override the host. An unrestricted `"url": "{{parameters.url}}"` is the unsafe form: the platform's request handling ignores Base `baseUrl` for a complete URL (Base headers still apply), so a user-typed absolute URL could send the connection's credentials to another server (hardening: add the fixed prefix and approve with adjustments, never reject), which the [universal module page](https://developers.make.com/custom-apps-documentation/app-components/modules/universal-module) says relative-only input exists to prevent. A fixed Base `baseUrl` alone does not close this. This is teaching guidance on a synthetic fixture, not a complete validator, and it does not claim live execution or that any provider or Make runtime was exercised. Whether the Base-auth header collides is a separate unknown (Check 2). Check 1, customization: the input exists (any equivalent name counts) and its value reaches the request headers through the spread. The caller can send `X-Api-Version`. No finding. Had there been no such input, the finding would be a REST capability gap, with impact raised because the provider requires a header, and still not a claim about authentication. @@ -106,7 +106,7 @@ Record each applicable check as a row; opening a guide is not the same as applyi | Source | Rule | Applies because | Exception considered | Status | Evidence | Finding | | --- | --- | --- | --- | --- | --- | --- | | [dates-helpers](dates-helpers.md) | Output datetime: traced Date-producing conversion + `date` interface | `createdAt` emitted, zone documented UTC, non-ISO text converted by `parseDate` | date-only, time-only, unknown zone, numeric id | `passed` | output expression and interface entry locations | none | -| [dates-helpers](dates-helpers.md) | Raw canonical ISO text, `date` interface, no traced conversion | Emitted datetime from HTTP JSON | already a traced Date value; documented exceptions | `uncertain` (recommendation; source ambiguity, ISO spelling or interface does not prove conversion) | output expression, interface entry | explicit-conversion recommendation, not a blocker or runtime claim | +| [dates-helpers](dates-helpers.md) | Raw canonical ISO text, `date` interface, no traced conversion | Emitted datetime from HTTP JSON | already a traced Date value; documented exceptions | `finding` (ISO spelling or interface does not prove conversion) | output expression, interface entry | parse with the provider's format; Required in marketplace review, not a runtime claim | | [dates-helpers](dates-helpers.md) | Cursor maps directly | Trigger `type: date`, field established as the documented comparable ISO form | merely ISO-looking value; not an output exemption | `not_applicable` for parse | trigger block | none | | [headers-merge](headers-merge.md) | REST header customization | REST universal module | GraphQL subtype | `passed` | input and its header sink | none | | [headers-merge](headers-merge.md) | Credentials retained | Module sets headers | unauthenticated endpoint | `uncertain` (collision) | merge expression | evidence needed, not loss | diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/rpc-page-budgets.md b/skills/make-custom-apps/examples/current-knowledge/guides/rpc-page-budgets.md index 4ea6d2d..ca38920 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/rpc-page-budgets.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/rpc-page-budgets.md @@ -25,6 +25,60 @@ Notice what this means: "150 records at 50 per page" is the 3×page recommendati } ``` +### When a page is not a list of records + +**Documented behaviour.** Without `iterate`, `output` is evaluated once on the response body (the body itself when `output` is absent), and that value is the page's result. + +**Inferred implementation pattern.** Make requests the next page only while the page's result is a non-empty list. Two shapes never produce one: a dynamic fields or interface RPC whose `output` builds one object from the page (for example a single `collection` whose `spec` a helper builds from `body.data`), and a request step without `output` that only copies the page into `temp` while the provider answers with an object. Their `pagination` block never sends a second request, even when its `condition` is true and the provider's cursor, count or has-more flag says more records exist. The fields or records from later pages are silently missing and the execution stays green. + +Choose one of these instead: + +* When one request at the provider's maximum page size covers every record the endpoint can return, ask for that size and drop the `pagination` block, so the configuration does not suggest paging that never happens. +* Otherwise collect the pages into `temp` with a bounded `repeat` that stops on the provider's next-page signal and on a page cap ([requests-files-multistep](requests-files-multistep.md)), and build the object in the same step's `output`. `response.temp` is applied before `output`, and the last repetition's output, built from every collected page, is the result. Put the cap in the condition and keep the literal `limit` above it as a safety net; reaching the `limit` is not the way the loop should end. + +```json +{ + "url": "/fields", + "qs": { "limit": 100, "page": "{{ifempty(temp.page, 1)}}" }, + "response": { + "temp": { + "records": "{{merge(ifempty(temp.records, emptyarray), body.data)}}", + "page": "{{ifempty(temp.page, 1) + 1}}", + "more": "{{body.has_more}}" + }, + "output": "{{buildFieldsSpec(temp.records)}}" + }, + "repeat": { "condition": "{{temp.more && temp.page <= 5}}", "limit": 10 } +} +``` + +Choose the cap from the provider's documented maximum and the 40-second budget, and test with more records than one page holds: the result must contain records from the second page. + +### Counting chunks by hand in a `repeat` loop + +**Documented behaviour.** A `repeat` request always runs once; its condition is evaluated after each request and reads `temp`. `slice(array; start; end)` counts from 0 (the first item has index 0), unlike `get` and `[n]` access, which count from 1. + +**Inferred implementation pattern.** When an RPC sends a list in fixed-size chunks (for example one batch call per 100 IDs to fetch labels), store the list in `temp.items` and a counter `temp.page` of 1 in an earlier step, advance the counter in `response.temp`, and derive both the slice and the stop from that one counter. When the condition runs, the counter already names the next chunk, so `(temp.page - 1) * temp.size` is the number of items sent so far: + +```json +{ + "condition": "{{length(temp.items) > 0}}", + "url": "/labels/batch", + "method": "POST", + "temp": { "size": 100 }, + "body": { "ids": "{{map(slice(temp.items, (temp.page - 1) * temp.size, temp.page * temp.size), 'id')}}" }, + "response": { + "temp": { + "page": "{{temp.page + 1}}", + "labels": "{{merge(ifempty(temp.labels, emptyarray), body.data)}}" + } + }, + "repeat": { "condition": "{{length(temp.items) > (temp.page - 1) * temp.size}}", "limit": 20 } +} +``` + +Two plausible-looking variants lose items without an error. Stopping on `length(temp.items) >= temp.page * temp.size` looks one chunk ahead and drops the last partial chunk: a list of 150 sends only the first 100. Stopping on `length(temp.items) >= (temp.page - 1) * temp.size` and shifting later slices by `+ 1` skips one item per later chunk (index 100, 200, and so on) and sends an empty request when the length is an exact multiple of the size. Gate the step with a `condition` so an empty list sends no request. Test lists of 0, size, size + 1, 2 × size and 2 × size + 1 items and check that every item is sent exactly once and that no request is empty. Each chunk is one more request inside the RPC's 40 seconds, so bound the list so that its chunks fit both that budget and the literal `repeat.limit`. + ## Choosing the numbers 1. Find the provider's maximum and default page size; use a size at or below the maximum. @@ -35,6 +89,30 @@ Notice what this means: "150 records at 50 per page" is the 3×page recommendati The checker's `CK-BUDGET-PAGE` rule tests that a fixture's `qs.limit` equals its declared page size, that records do not exceed pages × size, that stated numbers stay within the documented hard limits, and that the next-page expression agrees with the first request's page base. `CK-BUDGET-BOUND` tests that `response.limit` is a positive fixed integer within the declared record budget. That is a deliberately narrow fixture restriction (the literal form is the convention); it does not claim that every mapped limit is wrong on the platform, and the checker is not broadened to evaluate bounded expressions. +### When the help text states the list size + +**Inferred implementation pattern.** Help such as "Select (from the first 500) or map the ID" or "Shows up to 300, newest first" is a promise about the RPC. Three numbers must agree: the size in the help, what the requests actually ask the provider for (page size × pages), and `response.limit`. `response.limit` only cuts the result and only a paging request fetches more; neither raises the page size. A request that sets no page size receives the provider's default page (for example 25 records), so a selector with `response.limit: 500` and "first 500" in its help can show 25 options. A user who does not find the record in the short list is not told that it was cut off, and so does not know to map the ID. + +* Set the page size explicitly in the request: in `qs`, or as an argument inside a GraphQL query or a JSON body when the provider takes it there. +* Paginate, or not, so that page size × pages reaches the stated number within the budget above, and set `response.limit` to that same number. +* Write the real number and order in the help, and keep the field mappable so a record outside the list can still be entered by ID (step 5 above; `mode: "edit"` where the module role calls for it, see [selectors-mode](selectors-mode.md)). +* Help text copied from a sibling selector often causes the mismatch, so check each selector against its own RPC. + +```json +{ + "url": "/graphql", + "method": "POST", + "body": { "query": "{ items(limit: 500) { id name } }" }, + "response": { + "limit": 500, + "iterate": "{{body.data.items}}", + "output": { "label": "{{item.name}}", "value": "{{item.id}}" } + } +} +``` + +The matching help reads "Select (from the first 500) or map the item ID." In a review, a disagreeing number is dropdown-budget advice (see Evidence and limits): fix the request size, or fix the help so that it states what the list really shows. + ## Where the rest of pagination lives This guide is about the *budget* of a dropdown. The protocol itself (cursor, offset, next URL), stop conditions, `mergeWithParent`, the time budget and trigger state are explained in [pagination-and-trigger-state](pagination-and-trigger-state.md). A raised request timeout does not raise the pagination or RPC ceilings; consult the component's own limit table instead of promoting a number seen in one example. @@ -51,6 +129,9 @@ A user opens a dropdown; two minutes of crawling is not acceptable and the platf * Putting a `delay` between pages and forgetting it eats the 40 seconds. * Fetching all pages for an RPC and filtering in IML when the provider supports a search parameter. * Raising the budget because "the user has 800 projects". That is a UX problem, not a limit to bypass. +* A `pagination` block on a request whose page result is one object (a helper-built field `collection`, or an object body that is only copied into `temp`). It never fetches the second page. +* A hand-counted `repeat` loop whose stop looks one chunk ahead, or whose `slice` start is shifted by `+ 1` because `get` counts from 1 (`slice` counts from 0). +* Help text that promises "first 500" while the request asks for the provider's default page. ## Exceptions and applicability @@ -64,6 +145,8 @@ A user opens a dropdown; two minutes of crawling is not acceptable and the platf * **Approval impact** ([Approval gating](../../../references/review-and-qa.md#2a-approval-gating)). A bounded option or dropdown RPC budget is the recommended design; its bounds and the 500-item output limit are advisory. A truncated budget is a class (a) defect only when a search, list or trigger that promises all matching records silently drops them; a broken page progression (for example skipping pages or ignoring a documented next-page signal) is class (a) wherever it occurs. * 3-request and 3×page-size budgets, the 300-500 range: **documented recommendation**. * Consistency between page size, qs and limit in a fixture: **inferred implementation pattern**. The checker does not call a provider, measure latency or know any real page maximum. +* `output` without `iterate` evaluated once per response, a `repeat` condition evaluated after each request and reading `temp`, and `slice` counting from 0: **documented behaviour**. That pagination does not go past a page whose result is not a list, that `response.temp` is applied before `output` and the last repetition's output is the result, the chunk arithmetic, and the agreement of help text, request page size and `response.limit`: **inferred implementation pattern**. +* **Approval impact of the new cases.** An inert `pagination` block, or a chunk loop that skips items, counts as the broken page progression above when the provider can return more than one page or the list can exceed one chunk; fix it. When one request at the provider's maximum covers every possible record, the unused block is only misleading configuration and advisory. A help-text list size that disagrees with the request is advisory: fix the number or the text. ## Fixtures @@ -84,3 +167,7 @@ Static, synthetic teaching fixtures. The numbers in them illustrate the declared * https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-sample-rpc * https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/limit * https://developers.make.com/custom-apps-documentation/component-blocks/epoch +* https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/output +* https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests#repeat +* https://help.make.com/array-functions +* https://help.make.com/general-functions diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/selectors-mode.md b/skills/make-custom-apps/examples/current-knowledge/guides/selectors-mode.md index 4af5aca..7cc6c8e 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/selectors-mode.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/selectors-mode.md @@ -8,6 +8,23 @@ A select backed by a remote procedure call (RPC) lets users pick a record instea An option RPC returns an array of `{ "label": ..., "value": ... }` (`default: true` is optional). A select refers to it as `"options": "rpc://listProjects"` or in object form `{ "store": "rpc://listProjects", "nested": [...] }`. A fields RPC returns parameter specs (`name`, `type`, `label`, ...) and is referenced from `interface` or a `parameters` array, not from `options`. Using one where the other is expected is a schema confusion: the user sees the wrong thing, or nothing. +### Grouped options + +See [parameters and RPCs](../../../references/parameters-and-rpcs.md#grouped-options) — the `grouped: true` shape for long lists with natural categories, values unique across groups, and confirming RPC-loaded groups in the form. + +### Option order + +**Documented behaviour.** Options are unsorted by default and appear in the order they arrive. The select's `sort` attribute (`"text"` or `"number"`) sorts them in the form, which also replaces any order the RPC produced. When another order helps more (newest first), leave `sort` off and order the list before it reaches the select. Either ask the provider to sort (a sort query parameter), or sort in the RPC with the IML function `sort(array; [order]; [key])` ([array functions](https://help.make.com/array-functions)), where `order` is `asc`, `desc`, `asc ci` or `desc ci`. + +~~~json +"response": { + "iterate": "{{sort(body.items, 'desc', 'created')}}", + "output": { "label": "{{item.name}}", "value": "{{item.id}}" } +} +~~~ + +**Pitfall (not stated on the public page; confirm in the module).** The order comes before the key, and both are quoted strings. Written key-first, `sort(body.items, 'created', 'desc')`, the first argument is not an order keyword, so it is read as the key and the list comes back ascending. Written unquoted, `sort(body.items, desc, created)`, both arguments are empty variables and the list keeps the provider's order. Both forms pass upload and look plausible. Also, `iterate` runs once per response page, so an RPC-side sort orders each page, not the whole list. When the list spans pages and `response.limit` cuts it, prefer provider-side ordering so that the first options really are the newest. + ## Describing options that need explanation **Inferred UX guidance, not a documented requirement.** The public [Select page](https://developers.make.com/custom-apps-documentation/block-elements/parameters/select) documents the option forms (`value`/`label` pairs, `nested`, `store`) and the [mappable-parameters best practices](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters) cover select behaviour in mappable forms. Neither page gives guidance on an option-level `description`, so do not cite either as the source of that field or of this advice. It is a UX judgment: when the choices are not self-explanatory (for example two access levels whose difference the label cannot carry), and the authoring or editor schema you are working against accepts `option.description`, give each option its own short `description` next to `label` and `value`, instead of explaining the differing meanings in the field's help text or leaving users to guess. Verify that the section is accepted on upload and that the description is present in the read-back. If it is rejected or dropped, fall back to the field's help text. The shape, where accepted: @@ -57,6 +74,17 @@ A child select appears after the parent is chosen. The documented form is: **Inferred implementation pattern.** A child RPC that never reads its parent value loads the same list for every parent, so the nesting achieves nothing; one that reads a parameter that is not an ancestor reads something that may not be filled in. The checker's `CK-SELECTOR-NESTED` rule inspects the RPC text for those two cases. The parent still has to load: do not add `mode: "edit"` to the parent of a nested select merely to satisfy the mode rule, because that is not what the documentation's own nested example requires of every module kind. +**Documented form: nested fields from an RPC.** `nested` holds *parameters*, so besides an inline array it accepts an RPC URL. It can sit on the options object (`"options": { "store": ..., "nested": "rpc://getItemTypeFields" }`), so the fields follow whichever option is chosen. It can also sit on a single option (`{ "label": ..., "value": ..., "nested": "rpc://getOptionFields" }`), so the fields appear for that option only. That RPC is a fields RPC: it reads the chosen value from `parameters.` and returns parameter specs (`name`, `type`, `label`, ...), not `{label, value}` pairs. A fields RPC under `nested` is therefore correct and is not the options/schema confusion described in "The pieces"; an *options* RPC placed directly in `nested` is. + +~~~json +{ + "name": "itemType", "type": "select", "label": "Item type", "required": true, + "options": { "store": "rpc://listItemTypes", "nested": "rpc://getItemTypeFields" } +} +~~~ + +**Inferred implementation pattern.** A nested fields RPC may have nothing to add for some choices. A communication branch whose `condition` is false, or a `response.output` of `null`, returns no field, and nothing appears under the select. That is not a defect. Requiredness that depends on the choice follows "Conditionally required fields" in [parameters-and-rpcs](../../../references/parameters-and-rpcs.md#form-quality-ux-guidance-not-schema-rules). Test each choice, including one that adds nothing. + ## RPC inputs, parent values and what a picker must (not) cover * **Parameters reach RPCs automatically.** The module's parameters are passed to a linked RPC, and nested child RPCs also receive the parent's value. An RPC with an empty `parameters` declaration does not prove that module values are unavailable to it; the declaration describes the RPC's own inputs. Do not report a "missing parameter" on that basis alone. @@ -64,6 +92,9 @@ A child select appears after the parent is chosen. The documented form is: * **A picker is a convenience.** A dropdown does not need to list every object in a large account; a bounded sample plus manual mapping is a legitimate design ([rpc-page-budgets](rpc-page-budgets.md)). An ID missing from a sampled list is not invalid: mapped values are not restricted by the options, and static values are not validated against RPC-loaded options. Likewise, the absence of a picker proves a defect only when the provider offers a lookup and the task's scope includes one. * **Connection lists must match.** An RPC's connection list has to match the parent module's, even when the RPC makes no request at all. * **Metadata-driven options.** Keep the provider's stable identifier as `value` and the display text as `label`. Two options with the same label must not collapse into one choice. See [dynamic-data-and-files](dynamic-data-and-files.md) for schema-style RPCs. +* **Fixed context through the `rpc://` query string (documented).** One RPC can serve several fields that differ slightly: `"options": "rpc://listItems?status=open"` passes `status` to the RPC as `parameters.status`, and a repeated key sends an array. Whether a value such as `active=false` arrives as text or as a boolean, and which value wins when a module field has the same name, are not documented, so do not test such an argument for truthiness. The checks are in [parameters and RPCs](../../../references/parameters-and-rpcs.md#fixed-arguments-in-an-rpc-reference). +* **A picker must list from the scope the module acts in (inferred implementation pattern).** An RPC inherits Base, not the calling module's own `headers` or `qs`. When modules scope each request with a value from a module field (an organisation, workspace or tenant header or query parameter), every RPC behind a select or search button of those modules has to send the same value, read from the same `parameters.` (module parameters reach linked RPCs automatically). Otherwise the picker lists records from the account's default scope while the module reads or writes another, and the user picks IDs that do not exist where the request runs. Compare each module's scoping header or query parameter with the RPCs its pickers call, and test with a non-default scope. A mapped scope value follows the "mapped parent" rule above. A picker that offers IDs the module cannot use is the functional failure named under Approval impact below. +* **Search button (ID finder) on a typed field (documented).** A text field with an `rpc` search button keeps the identifier a typed field, and after a pick it shows the **value**, not the label. `mode` belongs to selects, so do not report a missing `mode: "edit"` on such a field; its `rpc://` name must still resolve and the RPC must share the module's connection. Syntax, conventions and the search RPC: [parameters and RPCs](../../../references/parameters-and-rpcs.md#search-buttons-id-finder). ## Rationale @@ -77,6 +108,8 @@ The user-facing goal is simple: find the thing without knowing its ID, and still * Pointing `options` at a fields RPC, or `interface` at an options RPC. * Forgetting that a connection-less RPC cannot be called from a module that has a connection. * Expecting the label in mapping mode. Only the value arrives. +* A hand-written `options` value that is not the provider's exact value: label and value swapped (`{ "label": "item_group", "value": "Item group" }`), or casing that differs from the provider's enum. The value is what the request sends, so compare every hand-written value with the provider's documented list. A repeated identical entry shows twice in the dropdown. +* A select whose options each reveal a different nested field ("by state", "by date range"), translated by a helper that sends the first non-empty nested field in a fixed order. That ignores the user's choice. Branch on the select's own value instead (`{{switch(parameters.filterKind, 'state', parameters.state, 'range', parameters.range)}}`), and check that every option value is one the request or helper actually compares. A misspelt value that nothing compares goes unnoticed until a user picks it. ## Exceptions and applicability @@ -91,6 +124,9 @@ The user-facing goal is simple: find the thing without knowing its ID, and still * Search/List hierarchy and Create advice: **documented recommendation**. * Per-option `description` for options with differing meanings: **inferred UX guidance**. The public Select and mappable-parameters pages were checked and give no option-description guidance; the Select page supports only the adjacent option syntax (`value`, `label`, `nested`, `store`). Advisory only, depends on the schema in use accepting the field, and needs upload/read-back evidence. * Parent-value reading checks and the options/schema separation: **inferred implementation pattern** over declared fixtures. The checker does not run RPCs or know a provider's real hierarchy; it cannot tell a high-level from a low-level entity. +* `nested` as an RPC URL (on the options object or on one option), the grouped options syntax, the select `sort` attribute, `rpc://` query parameters and the search button (`rpc` with `label`, `url` and `parameters`; the field shows the value after a pick; no `default: true` there): **documented behaviour / syntax**. A search button for large, searchable record sets: **documented recommendation**. +* A nested fields RPC returning no field, an options RPC returning groups, and the IML `sort` argument order: **inferred implementation pattern**. None of these is stated on the public pages, although the `sort(array; [order]; [key])` signature itself is on the array functions page; what is inferred is how a key-first or unquoted call behaves. Re-test them in the module. +* Group design, the choice of option order, the picker-scope rule and the hand-written option checks: **inferred implementation pattern / inferred UX guidance**. These are advisory, except where a picker offers IDs or values that the consuming request cannot use (see Approval impact). ## Fixtures @@ -113,3 +149,7 @@ Static, synthetic teaching fixtures; the checker reads the declared RPC, paramet * https://developers.make.com/custom-apps-documentation/component-blocks/interface (the interface an RPC-backed schema fills) * https://developers.make.com/custom-apps-documentation/best-practices/remote-procedure-calls * https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters (mappable select behaviour; no option description guidance) +* https://developers.make.com/custom-apps-documentation/block-elements/parameters/select#grouped and #sort (grouped options syntax; `sort` attribute, unsorted by default) +* https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-options-rpc#search-button (search button: value shown after a pick, no `default: true`, `ifempty(..., undefined)` filters) and #send-query-to-rpc (`rpc://` query parameters, repeated keys as an array) +* https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-fields-rpc#select-parameter-with-nested-dynamic-parameters-under-a-specific-option (`nested` as a fields RPC on one option) +* https://help.make.com/array-functions (`sort(array; [order]; [key])`) diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/universal-modules-and-scopes.md b/skills/make-custom-apps/examples/current-knowledge/guides/universal-modules-and-scopes.md index 7f2ddd5..7bd59b3 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/universal-modules-and-scopes.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/universal-modules-and-scopes.md @@ -10,12 +10,60 @@ A universal module lets a user call any route of the provider through the app's For a REST universal module the documented shape is: a clear relative URL input (help text states the fixed base and gives a valid path example), the HTTP method, optional query pairs, optional headers, an optional body, and a useful response envelope (status, headers, body). Where providers have API versions, prefer a base that lets the user put the version in the relative path, as the REST page describes. GraphQL universal modules have their own documented conventions (query, variables, response handling) and should not be forced into the REST shape. +### Single-endpoint providers + +Some providers expose one endpoint per service and choose the operation with a request header (an action or target header, or a SOAP action), not with the path. A universal module for such a provider has no path for the user to enter: + +* Fix the whole `url` in the module. The host may still come from connection data, such as a region or a sandbox flag. The user cannot change the destination at all, which is what the relative-path rule protects, so a missing URL input on such a module is not a REST-convention finding. +* Replace the URL input with one required operation input. Its help names the fixed endpoint and gives a working operation example, as URL help would. +* Let the module build the protocol header from that input. Keep the optional Headers input merged with the collection spread so Base authorisation stays ([headers-merge](headers-merge.md)), and say in the help which headers the module already adds. + +```json +{ + "url": "https://service.{{connection.region}}.example.com", + "method": "POST", + "headers": { + "{{...}}": "{{toCollection(parameters.headers, 'key', 'value')}}", + "x-example-target": "ExampleService.{{parameters.operation}}" + }, + "body": "{{parameters.body}}", + "type": "text" +} +``` + +The user fills in one field, and the protocol detail stays inside the app, so the first call works without the user knowing the header format. + ## Keep the destination inside the service -* A fixed `baseUrl` (with or without a path prefix) is compatible with a relative user input. Formatting of a fixed prefix does not by itself prove the user can replace the host. +* A fixed `baseUrl` (with or without a path prefix) is compatible with a relative user input, but on its own it does not keep a complete URL typed by the user on the provider host (see the safe pattern below). Whether a fixed prefix in the module `url` lets the user replace the host depends on where the host ends: a `/` after the host keeps the input in the path, while a host that runs straight into the input (`https://api.example.com{{parameters.url}}`) does not. * A doubled slash at the boundary between a REST universal module's fixed prefix and the user's relative path is not a defect. The [REST universal-module documentation](https://developers.make.com/custom-apps-documentation/app-components/modules/universal-module/rest) explicitly permits a prefix ending with `/` and input starting with `/`, and says the extra slash is removed. Thus `https://api.example.com/` + `/v1/items` becomes `https://api.example.com/v1/items`. A direct provider call to `//v1/items` does not reproduce that Make request. Do not raise a finding or add a slash-stripping expression for this boundary alone. This documented rule does not establish normalization of repeated slashes elsewhere in the path. * An absolute URL typed by the user would be the boundary violation; relative-only is the documented rule. A module that accepts one is hardened (add a fixed prefix or validation), not rejected. +* Safe pattern (the REST page's good practice): put the fixed prefix in the module's own Communication `url`, directly before the input, ending with `/`: `"url": "https://api.example.com/{{parameters.url}}"` (the host may come from connection data). The prefix stops before the API version segment. The trailing `/` closes the host, so `@other.example` or `https://other.example` stays in the path. Base `baseUrl` alone does not make a bare `{{parameters.url}}` safe. The help names the base without the trailing slash and gives an example that starts with `/` and the version: "Enter a path relative to `https://api.example.com`. For example: `/v1/users`." The resulting double slash is removed automatically and is not a defect. Without such a prefix (for example a bare `{{parameters.url}}`), reject or strip an absolute URL (`scheme://` or a leading `//`) so the credential cannot be sent to another host; a module that already has the prefix needs no extra validation. Do not recommend a module that sends the user's input as the complete URL together with Base authentication. * Inheritance must keep working when users add headers: Base authorisation stays in place when the module's `headers` collection uses the spread ([headers-merge](headers-merge.md)). For REST universal modules, assess whether an optional header input (any equivalent mapped input) exists and reaches the request, whatever the provider; a missing one is at least a documented-convention recommendation, and a concrete defect when a required provider header cannot be sent. It is not proof that authentication fails, and absence of a Headers input is not by itself a REST-convention finding for GraphQL universal modules, whose documented shape is query/variables; independently check that any provider-required headers can still be sent ([headers-merge](headers-merge.md)). Empty customisation fields must not remove inherited authorisation either; test the effective request with empty and populated fields. +* When the provider serves API families from different hosts, a module select can supply the host label (`https://{{parameters.service}}.example.com/{{parameters.url}}`), but only from a closed list: set `mappable: false` on that select. `mappable` defaults to `true`, and a mappable select also accepts a mapped or typed expression that bypasses the options, so scenario data could replace the host. After the host, the rest of the safe pattern still applies: the fixed `/` and the relative input. Give each option its own help, either a nested URL input per option or a note that names that host, so the user sees the right base for the family chosen. A mappable host select is hardening: fix it with `mappable: false` and approve with adjustments. In a published app, setting a select's `mappable` to `false` is a documented breaking change for scenarios that map the field. There, keep the select mappable and turn its value into a fixed host in the `url` instead, for example `https://{{switch(parameters.service, 'runtime', 'runtime', 'api')}}.example.com/{{parameters.url}}`, so any other value falls back to a listed host ([maintenance](../../../references/maintenance.md)). + +```json +{ + "name": "service", + "type": "select", + "label": "Service", + "required": true, + "mappable": false, + "options": [ + { "label": "Management API", "value": "api" }, + { "label": "Runtime API", "value": "runtime" } + ] +} +``` + +* When the connection owner can enter the API base URL (a self-hosted or staging instance, usually optional with a default), Base, the connection check (which does not inherit Base) and the universal module each repeat the fallback, and all of them must expect the same shape of value. Ask for the host, or the host plus any fixed path, without the version segment, say so in the connection help, and let every consumer append the same suffix. The universal module's prefix then ends before the version, as the REST page asks, and its help example is right for both the default and a custom value. If the connection value includes the version while the module's default stops before it, the default works but every custom host gets the version twice (`/v1/v1/...`), so only self-hosted users break. Test the module with the default and with a custom value. When fixing a published app, keep the shape that existing connections already store and adjust the consumer that disagrees, so saved connections keep working. + +```text +Base: "baseUrl": "{{ifempty(connection.baseUrl, 'https://api.example.com')}}/v1" +Connection check: "url": "{{ifempty(parameters.baseUrl, 'https://api.example.com')}}/v1/me" +Universal module: "url": "{{ifempty(connection.baseUrl, 'https://api.example.com')}}/{{parameters.url}}" +Help: Enter a path relative to `https://api.example.com` or the connection's API URL. For example: `/v1/users`. +``` ## Scopes and the universal module @@ -28,6 +76,10 @@ OAuth apps that offer a universal module may need to reach endpoint groups whose An example parameter name or separator is not a cross-provider convention ([connections-and-oauth](connections-and-oauth.md)). +### Scope lists of the other modules + +**Documented guidance.** For an OAuth connection each module declares the scopes it needs, including those of its RPCs, and Make offers to extend the connection's permissions when a module needs a scope the connection was not granted before ([connections-and-oauth](connections-and-oauth.md)). **Inferred implementation pattern.** Build that list as the union of everything the module calls: each request of a multi-request communication, including one that runs only under a condition (such as a follow-up write of custom fields or a read before an update), and every RPC behind its selectors and dynamic fields (for example a read scope for a user or customer picker in a write module). A complete list then surfaces a missing grant while the scenario is built, not as a permission error during a run. A scope already in the connection's baseline grant makes the request work without a module entry. A missing entry is a functional finding only when a request needs a scope outside that grant: fix it by adding the scope and approve with adjustments. In a published app, the added scope makes existing connections ask for extended permissions, so say so in the fix ([maintenance](../../../references/maintenance.md)). Otherwise a missing entry is an advisory completeness note. Scope lists matter only for OAuth connections. + ## Authoring checklist in prose Decide the base and the version policy; write relative-path help with an example; expose method, query, headers and body with sensible types; keep the response envelope useful for mapping; keep authorisation inherited and credentials sanitised; handle provider errors with the shared directives ([errors-and-rate-limits](errors-and-rate-limits.md)); and test through the real connection with empty and populated optional fields. Review prerequisites for public apps are a separate scope from a narrowly scoped implementation task, so apply them when the task is about publication. @@ -40,7 +92,7 @@ A universal module is the only place where a user, not the author, decides the r * Accepting an absolute URL. * Reporting a doubled slash between the fixed prefix and the user's path as a broken request, or "fixing" it by stripping slashes. -* Treating a fixed prefix format as a host-replacement vulnerability. +* Treating a fixed prefix that closes the host with `/` as a host-replacement vulnerability, or a host that runs straight into the input as safe. * A header input that, when empty, wipes inherited authorisation, or a `{{...}}` mistake that does the same. * Treating missing header customisation as broken authentication. * Requiring an extra-scopes field on every OAuth connection. @@ -52,7 +104,8 @@ A universal module is the only place where a user, not the author, decides the r * Apps without a universal module need none of this. * The versioned-path guidance depends on the provider's API versioning. * Provider restrictions on allowed destinations or content still apply. -* **Approval impact** ([Approval gating](../../../references/review-and-qa.md#2a-approval-gating)). A universal module input that untrusted scenario data could use to steer the connection's credential to another host is hardening: add a fixed prefix or validation and approve with adjustments. A credential placement the provider accepts (header, query string, body, Basic auth) is correct, and a host, subdomain or instance URL entered by the connection owner is a Make feature; neither is a defect. Only the app author's own code sending credentials or user data to a party other than the provider, without the user choosing it, is a scam and rejects. A doubled slash between the fixed prefix and the user's path is not a finding at all, because Make collapses it before sending (see above). Other path normalization effects, and scope or header conventions without a shown failure, are advisory, or `needs_evidence` only if the open question could hide a scam (unsettled, it rejects and names the missing fact). A header input that can wipe inherited authorisation makes calls fail (class (a)): fix it with a guard; it is a class (b) finding, fixed by the guard or the binding, when protected data or actions would be exposed without authentication. +* **Approval impact** ([Approval gating](../../../references/review-and-qa.md#2a-approval-gating)). A universal module input that untrusted scenario data could use to steer the connection's credential to another host is hardening: add the fixed prefix of the safe pattern above or validation and approve with adjustments. A credential placement the provider accepts (header, query string, body, Basic auth) is correct, and a host, subdomain or instance URL entered by the connection owner is a Make feature; neither is a defect. Only the app author's own code sending credentials or user data to a party other than the provider, without the user choosing it, is a scam and rejects. The double slash of the safe pattern (prefix ending with `/`, input starting with `/`) is removed automatically and is not a finding. Other path normalization effects, and scope or header conventions without a shown failure, are advisory, or `needs_evidence` only if the open question could hide a scam (unsettled, it rejects and names the missing fact). A header input that can wipe inherited authorisation makes calls fail (class (a)): fix it with a guard; it is a class (b) finding, fixed by the guard or the binding, when protected data or actions would be exposed without authentication. +* A module with no connection that sends to a complete URL the user supplies (an inbound webhook URL the provider issued, or a result URL mapped from an earlier module) is outside the relative-path rule. That rule protects the connection's credential, and there is none here, so this is not a universal-module boundary finding. Check the effective request instead. An absolute URL skips only Base `baseUrl`. Base headers and query defaults still apply, so a credential that Base adds from common data or as a fixed value would go to the user's host. Drop the inherited values with a whole-expression `headers` (or `qs`) value ([headers-merge](headers-merge.md)), or keep such values out of Base. A secret the user types into the module for that host goes only where the user chose. Send its header only when the field has a value, and list the header path in the module's `log.sanitize`. `type: password` does not mask it in a module ([labels-visibility](labels-visibility.md)). ## Evidence and limits diff --git a/skills/make-custom-apps/examples/current-knowledge/guides/webhooks.md b/skills/make-custom-apps/examples/current-knowledge/guides/webhooks.md index be98999..48e83e8 100644 --- a/skills/make-custom-apps/examples/current-knowledge/guides/webhooks.md +++ b/skills/make-custom-apps/examples/current-knowledge/guides/webhooks.md @@ -20,6 +20,83 @@ When attach or detach uses `connection.*` credentials, associate the intended co If detach reads a name attach never saved, detach cannot find the provider-side webhook and orphans pile up on the provider. The checker's `CK-WEBHOOK-IDENTITY` rule tests that every `webhook.` in detach is among attach's `response.data` keys. One-time secrets returned by attach must be persisted this way too, because the provider will not show them again; mask them in `log.sanitize` (`CK-SECRET-LOG`). +### One webhook, several provider subscriptions + +**Inferred implementation pattern** (documented `response.data`, `repeat`, `temp` and [request-less items](https://developers.make.com/custom-apps-documentation/component-blocks/api/request-less-communication)). Some attach RPCs create one provider subscription per selected event, with `repeat` or a `communication` array. When every pass writes the same `response.data` key, such as `externalHookId`, only the last id is kept. Detach then removes one subscription, and the others keep posting to a URL that no scenario listens to. `CK-WEBHOOK-IDENTITY` still passes, because detach reads a name that attach did save, so check the loop by hand. + +* If the provider accepts a list of events, prefer one subscription that covers all the selected events. +* With a fixed `communication` array, give each request its own `response.data` key, and give detach one request per key. +* With `repeat`, collect every id in `temp`, save the whole list on each pass, and make detach loop over it. `repeat` checks its condition after each request, so the first request always runs: make the event list required. `limit` must be a literal number; set it higher than the number of events a user can select. +* If a later pass fails, attach fails, and the subscriptions it already created can stay at the provider, because a failed attach saves nothing for detach to use. In detach, a 404 for one id that is already gone fails the loop at that id and leaves the rest. Test both cases. + +```json +{ + "attach": [ + { "temp": { "i": 1, "n": "{{length(parameters.events)}}", "ids": [] } }, + { + "url": "/subscriptions", + "method": "POST", + "body": { "url": "{{webhook.url}}", "event": "{{get(parameters.events, temp.i)}}" }, + "response": { + "temp": { "ids": "{{add(temp.ids, body.id)}}", "i": "{{temp.i + 1}}" }, + "data": { "externalHookIds": "{{temp.ids}}" } + }, + "repeat": { "condition": "{{temp.i <= temp.n}}", "limit": 20 } + } + ], + "detach": [ + { "temp": { "i": 1, "n": "{{length(webhook.externalHookIds)}}" } }, + { + "condition": "{{temp.n > 0}}", + "url": "/subscriptions/{{get(webhook.externalHookIds, temp.i)}}", + "method": "DELETE", + "response": { "temp": { "i": "{{temp.i + 1}}" } }, + "repeat": { "condition": "{{temp.i <= temp.n}}", "limit": 20 } + } + ] +} +``` + +### An empty detach: forgotten or deliberate + +**Inferred implementation pattern** (documented detach purpose). Detach deletes from the provider what attach registered. Some exported detach files contain only comments, such as an unedited template, and no `url`. Such a detach makes no request, so the provider keeps posting to a Make URL that no longer exists. This is not a missing export, which stays `uncertain`: the file is there, and it is empty. When the provider documents a removal route, it is the missing-detach case in [Evidence and limits](#evidence-and-limits). In an app with several webhooks, open every detach file, because one forgotten template can sit next to correct ones. + +When the provider documents no way to remove the registration, an empty detach is the honest implementation. Do not invent a removal call. Do not overwrite the registration with an empty or dummy callback either, unless the provider documents that as removal, because the overwrite can have side effects of its own. Make the limitation visible instead: give the reason in a detach comment, and tell users in a `warning` banner in the webhook's parameters that deleting the webhook in Make does not unregister it at the provider (see [Providers that keep only one registration](#providers-that-keep-only-one-registration)). A reviewer checks the claim against the provider documentation. + +```jsonc +{ + // Intentionally empty: the provider documents no route to remove this registration. + // The webhook parameters show a warning banner about this. +} +``` + +### Providers that keep only one registration + +**Inferred implementation pattern** (documented `warning` banner). Some providers keep a single callback per account, resource or topic. Registering a new URL silently replaces the previous one, and the earlier scenario stops receiving events without any error. Tell users before they create the webhook: put a `warning` banner in the webhook's parameters that names the scope and the effect. Keep the text within the recommended 50 to 300 characters. + +```json +[ + { "type": "banner", "theme": "warning", "title": "One webhook per workspace", "text": "Only one webhook per workspace is supported. Creating a new webhook replaces the previous one, which then stops receiving events." } +] +``` + +The same constraint affects detach. When a newer webhook has replaced the registration, the older webhook's detach can remove the registration that the newer one depends on. Clean up only the exact remote subscription that attach created ([webhooks and polling](../../../references/webhooks-and-polling.md#implement-attach-and-detach-together), step 6). Detach sees only what attach saved. So if the provider can report its current callback, save `webhook.url` in attach's `response.data` (for example as `hookUrl`), read the current callback first in detach, and remove it only when it equals `webhook.hookUrl`. + +### A registration that did not happen must fail attach + +**Documented behaviour** ([valid](https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/valid)). Without `valid`, a response with a status from 200 to 399 is valid. Some providers answer a failed registration with a 200 and an error envelope, for example GraphQL `errors` or `success: false`. Without `valid`, attach then succeeds anyway: the user sees a webhook that looks created but never receives an event, and detach later runs with an empty id. + +**Inferred implementation pattern.** Make attach fail on the value that proves the registration, usually the id that `response.data` saves. The message below is a fallback; add the provider's documented error field to it ([errors and rate limits](errors-and-rate-limits.md)). + +```json +{ + "response": { + "valid": { "condition": "{{body.id}}", "message": "The provider did not register the webhook: no webhook id in the response." }, + "data": { "externalHookId": "{{body.id}}" } + } +} +``` + ## Verification versus signatures **Documented behaviour.** The webhook specification has a `verification` block with a `condition` and a `respond`. It exists for providers that send a challenge: when `condition` (an expression over `body`, `query`, `headers`, `method`) is true, Make sends the `respond` and does not run the trigger. Example: `"condition": "{{if(body.code, true, false)}}"` with `status: 202`. @@ -34,6 +111,24 @@ A challenge reply proves that the endpoint answered a handshake. It is not reque * A helper called `verifySignature` or a declared secret field proves nothing about security by itself. * That a generic fixture cannot demonstrate a provider's signature scheme does not make provider verification optional. When a provider documents signing, the author still has to test it against the real provider (see [compatibility-evidence](compatibility-evidence.md)); the missing proof is a gap to close, not a reason to skip the check. +### Signature checks: traps to look for + +**Inferred implementation pattern.** This guide still demonstrates no signature scheme, and the raw-bytes rule above still applies. When an app checks a provider's signature in the webhook's own communication, look for these traps. Each one fails silently. + +* **HMAC arity.** `sha256` returns an HMAC only when a key is given, and the key is the third argument, after the output encoding: `sha256(message, 'hex', secret)` ([text functions](https://help.make.com/text-and-binary-functions)). `sha256(message, secret)` passes the secret as the encoding and returns a plain hash, so the comparison never matches. `sha1` and `sha512` take the key in the same place. +* **Hyphenated header names.** Read them with backticks, as in ``headers.`x-signature` `` ([IML](https://developers.make.com/custom-apps-documentation/block-elements/iml)). Without backticks, `headers.x-signature` is read as a subtraction. +* **The secret.** Attach saves a per-webhook signing secret in `response.data` and masks it, as in [Attach and detach identity](#attach-and-detach-identity). In a dedicated webhook, the receiver reads saved values through `parameters` or its alias `data`. +* **Rejecting a failed check.** Compute `respond.status` (an IML string) so that a failed check gets a 4xx, and let `output` yield no bundle in that case. A 4xx here answers a rejected delivery, so it is not the accepted-delivery pitfall below. Do not gate the check with a top-level `condition`: it can end processing before `respond`, and the provider then gets Make's default success answer. Some apps reject through `verification` with an inverted condition and a 4xx. That also rejects, but this guide keeps `verification` for challenges, so new code uses `respond`. The checker's `CK-WEBHOOK-VERIFY` and `CK-WEBHOOK-DELIVERY` model accepted requests only and expect a literal 2xx status, so neither checks a computed rejection status. + +```json +{ + "respond": { "type": "json", "status": "{{if(temp.accepted, 200, 401)}}", "body": { "accepted": "{{temp.accepted}}" } }, + "output": "{{if(temp.accepted, body, false)}}" +} +``` + +Here `temp.accepted` holds the result of the provider's check, computed in the receiver's `temp`. The public page does not state the order in which the receiver evaluates these directives, so prove the gate before you rely on it. Test a genuine, a tampered and, when the provider sends a timestamp, a stale delivery against the real provider (see [compatibility-evidence](compatibility-evidence.md)), and confirm that each rejected delivery gets the 4xx and produces no bundle. Never describe the check as verification that Make performs. + ## Delivery and acknowledgement **Documented behaviour.** The webhook's `respond` sets the HTTP answer to the provider (`type`, `status`, `headers`, `body`). Providers usually retry unless they receive a 2xx. `iterate` splits a payload into several bundles, `output` shapes each one, and an instant trigger yields exactly one bundle per webhook delivery. Instant-trigger parameters are static only, communication is optional, single request, with no iterate or pagination in the trigger's own communication. diff --git a/skills/make-custom-apps/references/base-and-connections.md b/skills/make-custom-apps/references/base-and-connections.md index 948fa8b..bb22f69 100644 --- a/skills/make-custom-apps/references/base-and-connections.md +++ b/skills/make-custom-apps/references/base-and-connections.md @@ -40,6 +40,57 @@ Sources: [Base](https://developers.make.com/custom-apps-documentation/app-compon [Advanced inheritance](https://developers.make.com/custom-apps-documentation/app-components/base/advanced-inheritance.md), [Connection inheritance and CA configuration](https://developers.make.com/custom-apps-documentation/other/https-custom-ca.md). +### Client certificates (mutual TLS) + +When the provider authenticates the client by certificate as well as by token, collect the PEM +certificate with a `cert` parameter and the PEM private key with a `pkey` parameter (both are +documented parameter types). Name the expected file format in the help text, keep any other secret +(such as a client secret) a `password`, and mark the certificate and key `editable` so a rotated +certificate does not force a new connection. + +Send the pair with the `cert` and `key` request directives in Base and in every connection request +that reaches the certificate-protected host. Connection communication does not inherit Base, and, +as the custom-CA guide documents for `ca`, each OAuth 2.0 request (`token`, `refresh`, `info`) +carries its own configuration, so a value at the top level of an OAuth 2.0 communication does +nothing. If the pair is left out of Base, the token request can succeed while +every module call fails the TLS handshake. + +```json +{"cert": "{{connection.certificate}}", "key": "{{connection.privateKey}}"} +``` + +In the connection's own requests, read the same values as `{{parameters.certificate}}` and +`{{parameters.privateKey}}`. `cert` and `key` are not on the public request reference; they are +seen in approved apps, so prove the wiring with a real connection and one module call, not from +the definition alone. + +Sources: [Cert parameter](https://developers.make.com/custom-apps-documentation/block-elements/parameters/cert.md), +[Pkey parameter](https://developers.make.com/custom-apps-documentation/block-elements/parameters/pkey.md), +[Connection inheritance and CA configuration](https://developers.make.com/custom-apps-documentation/other/https-custom-ca.md). + +### Apply one host rule everywhere + +When the host depends on connection values (subdomain, tenant, region, environment or a +self-hosted URL), write the rule once and use the same expression in Base, in the connection's +own requests, and in every module or RPC whose URL leaves Base. The documented variable base URL +example puts the condition in both the connection and Base for this reason. Two failures seen in +approved apps: + +- The connection check goes to a fixed host. It proves only that the key works somewhere, so a + wrong subdomain or workspace ID is accepted at connect time and every module fails later. Check + against the host built from the submitted values, preferably on a path that includes the tenant + identifier, so both are verified. +- A component needs a second host (for example a separate messaging service). One module derives + it from the connection while the matching RPC hard-codes it, so a self-hosted connection lists + from one server and writes to another. Use the identical expression in both. + +```json +{"url": "https://{{parameters.subdomain}}.example.com/api/v2/workspaces/{{parameters.workspaceId}}"} +``` + +Sources: [Base URL](https://developers.make.com/custom-apps-documentation/best-practices/base/base-url.md), +[Variable base URL](https://developers.make.com/custom-apps-documentation/app-components/base/base-url.md). + ## Use the right variable context | Context | Read or write | @@ -59,6 +110,20 @@ Sources: [Basic variables and persisted data](https://developers.make.com/custom [OAuth variables and flow](https://developers.make.com/custom-apps-documentation/app-components/connections/oauth2.md), [Common data](https://developers.make.com/custom-apps-documentation/app-components/connections.md#common-data). +### Trace every `connection.*` read to a writer + +In Base, modules, RPCs and webhooks, `connection.X` holds only what the connection stored: one of +its parameters or a key written by `response.data`. A key that nothing stores does not raise an +error; it evaluates to empty. `if(connection.sandbox, 'sandbox.', '')` then never selects the +sandbox host, and help text or URLs built from an unstored region render broken. For each distinct +`connection.*` key, find the parameter or `response.data` assignment in every connection the +component accepts; a key that only one connection variant stores is empty for the others. Declare +the parameter (and use it in the connection's own requests too, as the documented sandbox example +does) or store the value. + +Sources: [Variable base URL](https://developers.make.com/custom-apps-documentation/app-components/base/base-url.md), +[Basic connection data](https://developers.make.com/custom-apps-documentation/app-components/connections/basic-connection.md). + ## API key and HTTP Basic validation 1. Collect secrets with `password` parameters and provider-specific labels. @@ -120,6 +185,44 @@ Sources: [Basic connection](https://developers.make.com/custom-apps-documentatio [OpenAPI 3.0.3 Security Scheme Object](https://spec.openapis.org/oas/v3.0.3.html#security-scheme-object). Worked contrast: [auth evidence worked](../examples/current-knowledge/guides/auth-evidence-worked.md). +### A check that every module-capable credential passes + +Pick the check so that it succeeds for every credential that can run the modules; the +validation-endpoint guidance asks for an endpoint "that will work in every case". Providers that +authorise per action (scoped keys, policy-based permissions) can reject a valid, narrowly scoped key +on a convenient list call that no module makes. Prefer, in this order: an identity, account or +token-introspection call that any valid credential may make; then a cheap, bounded read (page size +1) that the modules themselves need. A lookup of a fixed record (a hard-coded domain, email or ID) +is not such a call: its result depends on data outside the user's account, and on usage-metered APIs +it spends quota on every check. If no call fits, state in the connection help which permission the +check needs, so a missing permission is not mistaken for invalid credentials. A list call is fine +when every supported key can make it. In review, replace an existing check only with provider +evidence that a supported key lacks the permission it needs. Without a shown failure, a weaker check +stays advisory (see the gate below). + +Source: [Validation endpoints](https://developers.make.com/custom-apps-documentation/best-practices/connections.md). + +### Bind the connection label to a returned field + +`response.metadata`, in `info` or in the single request of a Basic connection, is the label that +lets a user with several connections to one service tell them apart. It takes `type` (`text` or +`email`; use `email` only for an email address) and `value`; Make sets a limit of 512 characters for +a string, so keep the label short. Bind `value` to a field the check response really returns. A path +the response lacks (for example `{{body.email}}` on an endpoint that returns a list) and a zero +index (`{{body.items[0].name}}`; IML arrays start at 1) both evaluate to empty without an error, so +the connection simply shows no label. When the check returns no identity, use a non-secret value the +user entered (an account or company ID) or fixed text, never a credential, and confirm the label +against a real check response. Build the value from non-secret identity fields that every account +has (name, email, account or workspace name, user ID), never from a token or session identifier, not +even part of one. When the label joins optional fields, give each part a fallback, for example +`{{ifempty(body.account.name, body.user.email)}}`. A helper that joins parts must skip missing ones +and fall back to a stable value; a part that returns `false` or `undefined` produces labels such as +`false false`, so test it with missing parts, not only with a complete profile. A missing or empty +label is advisory. + +Sources: [Connection metadata](https://developers.make.com/custom-apps-documentation/best-practices/connections/connection-metadata.md), +[Basic connection metadata](https://developers.make.com/custom-apps-documentation/app-components/connections/basic-connection.md#metadata). + ## OAuth 2.0 lifecycle - Register the provider client and exact callback before implementing the flow. @@ -147,6 +250,71 @@ Worked contrast: [auth evidence worked](../examples/current-knowledge/guides/aut Source: [OAuth 2.0, expiry and token conditions](https://developers.make.com/custom-apps-documentation/app-components/connections/oauth2.md). +### Token conditions and edited connections + +Make evaluates `token.condition` against the stored connection data whenever a module is about to +use the connection, and when the connection is created or verified; when it is false, the stored +token is used. Two consequences for any `token` block with a condition (client credentials or +another grant that needs no user): + +- The condition can read only what the token response stored. When the connection has no stored + expiry, the documented condition is true, so a `token` whose `response.data` never writes + `expires` requests a new token on every use, exactly like `"condition": true`. Store the + provider's expiry, or a fixed lifetime such as `addMinutes(now, 55)` for a one-hour token. +- An expiry-only condition does not react to an edit. Changing the credentials, company or tenant + of an editable connection does not make `data.expires < ...` true, so the old token can stay in + use until it expires, and a verification after the edit can pass with that old token. One + pattern seen in approved apps: an advanced, editable boolean (for example `forceRefresh`, help: + request a new token after you edit this connection), checked before the expiry and written back + as `false` in `response.data` so it acts once; in connection communication `parameters` and + `data` are the same store. Without that reset, a ticked flag requests a new token on every use. + Prove the edit path with a real connection. + +```json +{ + "condition": "{{parameters.forceRefresh || data.expires < addMinutes(now, 15)}}", + "response": {"data": { + "accessToken": "{{body.access_token}}", + "expires": "{{addSeconds(now, body.expires_in)}}", + "forceRefresh": false + }} +} +``` + +Source: [token.condition](https://developers.make.com/custom-apps-documentation/app-components/connections/oauth2.md#token.condition). + +### Hosts returned by the authorization callback + +Some multi-region providers return the account's server in the authorization callback; the app +stores that query value through `authorize.response.data` and uses it as the host of `token`, +`refresh`, `info` and Base. The callback passes through the browser of whoever runs the flow, so +that person can change the value, and the token request then sends the authorization code, the +client ID and secret and later the refresh token to the host it names. When the client ID and +secret can come from the connection's common data (for example +`ifempty(parameters.clientSecret, common.clientSecret)`), a tampered callback hands the app's +shared secret to a host of the user's choosing. That differs from an owner-entered host, which the +gate below treats as a Make feature because the owner can only send their own credential: it is a +fixable class (b) finding (add the allowlist), not a reason to reject. When everything the token +request sends belongs to the user, the owner-entered rule applies and the allowlist is advisory. + +Accept the value only if it is one of the provider's documented hosts, before it is stored or used. +`authorize.response.valid` is evaluated against the callback query before the token request, so an +unknown host fails the flow there: + +```json +{"authorize": {"response": { + "valid": "{{query.server === 'https://accounts.example.com' || query.server === 'https://accounts.eu.example.com'}}", + "temp": {"code": "{{query.code}}"}, + "data": {"accountsServer": "{{query.server}}"} +}}} +``` + +Use an exact list, or a pattern anchored on scheme and full host suffix with no user info, port or +path; a substring or replace check passes unknown hosts through. A callback value inserted into a +host label (`https://{{connection.account}}.api.example.com`) needs the same care: allow only the +provider's identifier characters, because `/`, `?` or `#` end the host early. Test with every +documented region, an unknown host and a look-alike host. + ## OAuth 1.0, JWT, and request signing Use OAuth 1.0 when required by the provider: implement `requestToken`, `authorize`, @@ -167,6 +335,51 @@ Sources: [OAuth 1.0](https://developers.make.com/custom-apps-documentation/app-c [JWT](https://developers.make.com/custom-apps-documentation/app-components/connections/jwt.md), [Request signing](https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests.md#aws). +### Signed requests with the `aws` directive + +Some providers sign every request with an access key pair instead of sending a token. Make's +`aws` directive does the signing; put it in Base and read the pair from the connection. + +```json +{ + "baseUrl": "https://service.{{connection.region}}.example.com", + "aws": { + "key": "{{connection.key}}", + "secret": "{{connection.secret}}", + "sign_version": "4", + "service": "example-service" + } +} +``` + +- The documented property table lists `secret`, `session`, `bucket`, `sign_version` and `service`; + approved apps were seen passing the access key identifier as `key`; prove it with a real + signed call. +- Set `sign_version` to 4 explicitly; the documented default is 2. `service` applies only to + version 4 and must be the provider's signing name for the endpoint, which is not always the + first label of the host. A module that calls an endpoint signed under another service name + needs its own complete `aws` block. +- The directive has no documented region property. Approved apps on AWS hosts were seen keeping the + region in the host name, taken from one connection value (a required select), and set no region in + the block. For any other host whose signature includes a region, prove a non-default region with a + real signed call before relying on it. +- Collect the secret as `password`. The access key identifier is not the secret and may be `text`. +- The credentials appear only inside the signing block. When tracing which context reads each + credential, trace the `aws` block: a request with no Authorization header is not unauthenticated. +- Signing does not remove the need to mask. List `request.headers.authorization` (the signed + header carries the access key identifier) and, when `session` is set, + `request.headers.x-amz-security-token` in `log.sanitize`. An empty list does not show that + nothing needs masking. +- The connection does not inherit Base, and an unsigned check does not test the key pair. Approved + apps were seen signing the Basic connection check with the same block, reading `parameters.*`, + although the connection references list `aws` as not available there (see the caution above). + Treat a signed check as a runtime fact to prove: create one connection with a valid pair and one + with a wrong secret. Do not replace it with an unsigned request, and do not report it as a defect + from that reference line alone. + +Sources: [aws request directive](https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests.md#aws), +[Basic connection communication](https://developers.make.com/custom-apps-documentation/app-components/connections/basic-connection.md). + ## Current-knowledge guides - How connection, Base, modules and webhooks layer, with a map to the other guides: @@ -197,3 +410,17 @@ Sources: [OAuth 1.0](https://developers.make.com/custom-apps-documentation/app-c Approval impact follows [Approval gating](review-and-qa.md#2a-approval-gating): a consumer with no credential binding is a class (c) defect (fix it by binding the compatible connection; when several exist, choose the one the module's API and scopes require and state the choice), a user-entered secret in a non-password parameter is class (b) credential handling (change it to `password`; approve with adjustments), a host, subdomain, region or instance URL entered by the connection owner is a Make feature and not a defect, a credential placement the provider API accepts is correct, an omitted shared or external connection import is `needs_evidence` only if the open question could hide a scam (unsettled, it rejects and names the missing fact; otherwise advisory), and a connection check that may not distinguish valid credentials is advisory without evidence. Source: [Sanitization](https://developers.make.com/custom-apps-documentation/app-components/base/sanitization.md). + +### Leftover connection scaffolds + +Review every connection directory, not only the one the modules use. Approved apps were seen +shipping extra connections that still hold the editor's prefilled template: a check against a +placeholder host (`https://www.example.com/api/whoami`), the template comments and no help text. +While no module, RPC or webhook accepts such a connection it does no harm, so report it as advisory: +relabel it as not for use, or finish it with a real check, help text and the same host rule as Base. +Connections are app-scoped, not version-scoped, so check the modules, RPCs and webhooks of every +major version (`connection` and `altConnection`) before calling one unused, and suggest deleting it +only if it was never part of a released version. A connection that a component does accept but that +still points at the placeholder host can never pass its check; that is a functional defect to fix. + +Source: [Connections](https://developers.make.com/custom-apps-documentation/app-components/connections.md). diff --git a/skills/make-custom-apps/references/editor-schema-validation.md b/skills/make-custom-apps/references/editor-schema-validation.md index 0cf36c5..fcf6590 100644 --- a/skills/make-custom-apps/references/editor-schema-validation.md +++ b/skills/make-custom-apps/references/editor-schema-validation.md @@ -23,6 +23,45 @@ checked against `api-oauth.json` when it holds OAuth steps (`authorize`, `token` `install`, `installSpec` and the app metadata. The script lists them as not validated. Report them the same way: read them by hand, and do not count them as passed. +### The schemas do not parse IML + +Most expression fields are plain strings in the schemas, and the few that check for IML only require a `{{` +somewhere before a `}}`. Unbalanced parentheses therefore pass wherever an expression is allowed, and an +unclosed `{{` passes in every plain string field, such as a `url`. A clean result says nothing about +expression syntax. Check every `{{ }}` yourself, in every component and not only in module requests: RPC, +webhook and connection communication, `iterate`, `temp`, `output`, `pagination`, error `message` and +`attach`, including branches a test run rarely reaches. + +- Count `(` against `)` inside each `{{ }}` after removing quoted strings and backtick-quoted property names. A + parenthesis or brace inside them belongs to the string or the name, and GraphQL or JSON text around the + expression has its own braces. +- Make does not report the parse error. A parenthesis missing or extra at the very end of an expression is + usually closed silently and still returns the intended value, which is why the typo survives testing: + `{{map(parameters.ids, 'id'}}` still returns the IDs. Inside nested calls the same typo moves an argument to + another function without any error: `{{if(parameters.status, lower(parameters.status, 'open')}}` passes + `'open'` to `lower`, so an empty status returns empty instead of `open`. An unclosed `{{`, as in + `/items/{{parameters.id}/details`, is sent as literal text. +- It is still syntactically invalid IML, a class (a) defect even when the current output looks right + ([Approval gating](review-and-qa.md#2a-approval-gating)): the recovery is not documented behavior. Fix it by + adding the missing delimiter or deleting the extra one, and keep the rest of the expression unchanged. Where + the intended argument list is not clear, put the delimiter where the parser closes it today, so the current + behavior stays the same, and say so in the finding. + +### Specs built at runtime are not validated + +The schemas check component files only. Parameter and interface specs that a fields RPC, an interface RPC or +a custom function builds at runtime never reach the editor validation, so a clean result says nothing about +them. Read that code against `parameters.json` and the type pages yourself, with the rules in +[Dependent options, fields, and interfaces](parameters-and-rpcs.md#dependent-options-fields-and-interfaces): +valid keys, a Make `type` for every field (`text`, not `string`) and a `name` on every value-bearing +field (display-only banners need no name). A generated +`name` is the key under which scenarios save the mapped value and that the module reads, so check its spelling +before the first release. After release, changing an RPC or a function that builds dynamic parameters is a +documented breaking change: when a misspelled name is still read consistently, keep it and correct the `label` +instead ([Preserve existing contracts](maintenance.md#4-preserve-existing-contracts)). When the misspelling +breaks the request or the mapping, it is a class (a) defect: fix it and state the compatibility impact +([Approval gating](review-and-qa.md#2a-approval-gating)). + ## 2. Read the warnings An unknown key (`additionalProperties`) or an invalid enum value usually means the runtime ignores or misreads diff --git a/skills/make-custom-apps/references/iml-functions.md b/skills/make-custom-apps/references/iml-functions.md index e6307be..6da4a61 100644 --- a/skills/make-custom-apps/references/iml-functions.md +++ b/skills/make-custom-apps/references/iml-functions.md @@ -44,6 +44,55 @@ Prefer direct mapping when the provider accepts the supplied value and preserve Sources: [JavaScript-like IML, operators, indexing, and ifempty](https://developers.make.com/custom-apps-documentation/block-elements/iml.md), [Empty-value handling](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/processing-of-input-parameters.md#handling-arrays-nulls-and-empty-strings). +### toCollection on user-entered rows + +`toCollection(rows, 'name', 'value')` turns user-entered name/value rows into a collection, +and it does so quietly: a repeated name keeps only the last row's value, and a row with an +empty name is dropped. An empty or missing array gives an empty collection, so a spread +`"{{...}}": "{{toCollection(parameters.rows, 'name', 'value')}}"` adds nothing. Each value is +passed through unchanged, so it keeps the type its sub-field produced (text stays text). + +When you build or change such an array, especially one whose rows become body fields, query +parameters or custom fields: + +- mark the name sub-field `required`, so a row is not lost without a message; +- say in the array's `help` that a repeated name keeps the last value; +- give the value sub-field the type the provider expects. + +In an existing array these are advice, not a defect, unless a lost or overwritten row is +shown to break a request. + +### split() is not JavaScript split + +IML `split(text, separator)` trims each item and drops empty items: +`split('a, b,,c', ',')` returns `["a", "b", "c"]`, and a leading or doubled separator +creates no empty position. A comma-separated text input therefore needs no extra trimming +in IML, and a review should not report missing trimming there. Do not read positions with +`get(split(...), n)` when segments can be empty, because they shift. Inside a custom +function, `value.split(',')` keeps spaces and empty strings: use +`value.split(',').map((s) => s.trim()).filter(Boolean)` or call `iml.split()`. + +### URL-safe base64 + +`base64()` and `sha256(text, 'base64')` return standard base64 (`+`, `/` and `=` padding). +URL-safe base64 (`-` and `_`, usually without padding), as used by a PKCE +`code_challenge`, JWT segments and some message APIs, is not a built-in IML function. The +OAuth 2 PKCE example calls `base64url(...)`; that call works only when the app defines a +custom function with that name, and otherwise fails with a "function not found" error. +Without custom functions, convert in IML: + +```text +{{replace(replace(replace(sha256(temp.code_verifier, 'base64'), '+', '-'), '/', '_'), '=', '')}} +``` + +IML `replace()` with a plain search string replaces every occurrence. Inside a function, +JavaScript `'a+b+c'.replace('+', '-')` replaces only the first one, so use +`.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')`. Decoding needs no +conversion: `toBinary(value, 'base64')` accepts both alphabets, with or without padding. +Keep the encoding in one place and test it with input whose standard encoding contains `+` +and `/`. A challenge that still contains `+`, `/` or `=` does not match the verifier, so the +token exchange fails. + ## Custom function contract Pass all required values as explicit arguments. Do not assume a custom JavaScript @@ -68,6 +117,34 @@ performance or package availability reproduces the app runtime. Sources: [Function runtime and limits](https://developers.make.com/custom-apps-documentation/app-components/iml-functions.md), [IML built-ins and JSON conversion](https://developers.make.com/custom-apps-documentation/block-elements/iml.md). +### Serialize values instead of splicing them into text + +Treat names and values that come from the user, the connection or the provider as data for +a serializer, never as text to splice. JSON text built as `'{"' + name + '":' + ...` in a +function, or as `parseJSON('{"k":"' + parameters.k + '"}')` in IML, fails or gains extra +members when a table name, column, file name, free-text value or even an API key contains a +quote, a backslash or a line break. + +- In a function, build an object (`const out = {}; out[name] = rows; return out;`) and return + it, or pass it to `JSON.stringify()` when the caller needs a string. +- In IML, put the structure in the directive (`"body": {"k": "{{parameters.k}}"}`). +- When the body has to stay text, for example because a signature covers the exact sent + bytes, wrap every spliced value in `createJSON()` and guard optional values: when an absent + value arrives as `undefined`, `createJSON()` returns nothing and + `'{"k":' + createJSON(parameters.k) + '}'` becomes `{"k":}`. Use + `ifempty(createJSON(parameters.k), 'null')` or leave the member out. Outside this text-body + case, keep objects as objects ([requests-and-responses.md](requests-and-responses.md)). +- `escapeHTML()` (`iml.escapeHTML()` in a function) replaces only `&`, `<` and `>`. Inside a + quoted HTML attribute value, after `escapeHTML()`, also replace `"` with `"` (and `'` + with `'` in a single-quoted one). Replacing line breaks with `
` is formatting, not + escaping. +- In a MIME message, multipart part or other header block assembled as text, remove CR and LF + from every user value (header names and values, file names, display names), so a value + cannot start a new header line. + +Test each assembled text with a value containing `"`, `\`, a line break and non-ASCII text, +and with each optional value left empty, not only the happy path. + ## Reuse a small testable function The following function and the first two tests reuse the SDK's IML test example. @@ -176,6 +253,26 @@ are an evidence limitation and advice, not an automatic defect or approval block task's explicit review criteria or request-scope requirements (which can block when unmet) require them or the helper's actual behavior lacks essential evidence. Demonstrably incorrect behavior stays a finding. +### Run the shipped tests, not only read them + +Execute every shipped test against the current function source: with the editor's +**Run IML test**, or with the local harness above when the helper makes no `iml.*` call. A +test that cannot run locally only because the harness lacks `iml` is an evidence limit, not a +finding. Tests that fail or cannot run were seen in approved apps; look for these forms: + +- an assertion on a property the function never sets, such as + `assert.strictEqual(attr.time, false)` when the code never adds `time`; +- `strictEqual` against a fresh array or object (`assert.strictEqual(fn(x), [])`), which + always fails because `[] !== []`; use `deepStrictEqual`; +- a call the IML tests page does not document, such as a Jest-style + `expect(...).toEqual(...)` or a `require()` of a fixture or module. Rewrite it with `it` + and the documented `assert` functions. + +Report a red test, or one the editor's **Run IML test** cannot execute, as a finding. Decide +from the real call sites whether the test or the function is wrong, and fix that side: a wrong +function is a demonstrated defect; a wrong test alone is advisory under [Approval +gating](review-and-qa.md#2a-approval-gating) and is fixed because the fix is clear. + ## Transformation and verification gate - Test absent, null, empty-string, zero, false, and normal inputs where meaningful. @@ -193,3 +290,21 @@ evidence. Demonstrably incorrect behavior stays a finding. Sources: [Conditional empty removal](https://developers.make.com/custom-apps-documentation/app-components/iml-functions/removal-of-empty-collections-and-nulls.md), [Full-update behavior](https://developers.make.com/custom-apps-documentation/app-components/iml-functions/handling-of-full-update-approach-in-update-modules.md). + +### Normalize before hashing identifiers + +When a provider requires personal identifiers (email, phone, names, address parts) to +arrive hashed, its per-field normalization is part of the contract: a wrongly normalized +hash is accepted by the API and silently never matches. + +- Apply each field's documented rule (trim, lowercase, allowed characters, phone format) + before hashing, for example `sha256(lower(trim(parameters.email)))`. Rules differ per field + and per provider; do not copy them from another integration. +- Hash only present, non-blank values and leave the field out otherwise. `sha256()` of a + missing value fails the module, and `sha256('')` returns the digest of the empty string + (`e3b0c442…`), which a provider can accept as a real value. +- Pass fields the provider wants raw (for example an IP address or user agent) through + unhashed, and keep it visible which fields are hashed and which are raw. +- Use the digest encoding the provider expects; `sha256()` returns hex by default. +- Test mixed-case, padded, formatted and blank inputs against the provider's documented + examples. diff --git a/skills/make-custom-apps/references/maintenance.md b/skills/make-custom-apps/references/maintenance.md index 2ec03ee..31cafac 100644 --- a/skills/make-custom-apps/references/maintenance.md +++ b/skills/make-custom-apps/references/maintenance.md @@ -19,6 +19,28 @@ A public-only filter is a published-impact reporting choice, not a general maint Preserve unknown visibility; do not infer public status from labels, approval flags or missing fields. Hiding a module does not disable existing scenarios that use it.[6] +### Find every copy of the provider version + +A version pinned as a header or path literal often lives in more than one place, and a Base change moves +only the components that inherit it. Before a version upgrade, list every literal and classify each copy: + +| Copy | Why it exists | Upgrade action | +| --- | --- | --- | +| Base `headers` or `baseUrl` | The single source that modules and RPCs inherit. | Change it here. | +| Connection check | Connection communication does not inherit Base. | Change it in the same edit as Base when the check calls a versioned endpoint, and re-check any `response.data` or `metadata` it reads from the response, since another version can return another shape. | +| Connection token or refresh request | Connection communication does not inherit Base; many providers do not version their auth endpoints. | Change it only when the provider versions that endpoint, and handle it as an authentication migration (section 4), not as part of the version edit. | +| Module or RPC header with the same value as Base | A same-named module header wins over Base, so it keeps the old value after Base moves. | Change it in the same edit as Base, or remove it so the component inherits; both send the new version. | +| Module or RPC that rebuilds headers by hand (a whole-expression `headers`, or a `temp` copy of auth and version) | A whole-expression `headers` replaces Base, so the credential and version were copied. | Change every copied header; for new work, prefer the `"{{...}}"` spread so Base stays the source ([headers-merge](../examples/current-knowledge/guides/headers-merge.md)). | +| Universal module whose fixed prefix stops before the version segment | The user's relative path carries the version. | Update the version in the help example only; keep the prefix, and leave saved paths as users wrote them. | +| Pre-filled header row or other parameter `default` | A user-facing copy of the version. | Update it with Base; do not assume a changed default reaches scenarios that already saved the old value, and check which value the effective request sends. | +| Communication fallback such as `ifempty(parameters.version, '')` | A code default for an empty input. | Update it with Base; it changes the request of every scenario that leaves the input empty. | +| Component with a different value on purpose | It needs a feature that only another version offers. | Keep it, with a comment that names the reason, and re-check it at every upgrade. | + +Read the effective request of webhook attach and detach calls before assuming they inherit Base. +Record each copy in the version evidence so the upgrade diff shows it changed or deliberately kept. +Base is the single source only for the modules and RPCs that inherit it. A copy left off this list is how +a connection check, an RPC and a module end up on different versions that return different response shapes. + ## 2. Evaluate every relevant provider change Collect and deduplicate the relevant official changelog, reference and migration URLs. @@ -84,6 +106,44 @@ For deprecations, use documented warnings/help and compatible alternatives where silently deleting an input. Announce removals before rollout through the approved communication process.[32] Do not infer permission to contact users or post release announcements from a maintenance request. +### Adapt a changed provider response instead of changing the published output + +When a provider version moves data (a field becomes `null` and its value appears in new sibling fields, +a value moves under a nested object, a serialized string splits into typed fields), changing the published +output or interface to follow it breaks existing mappings.[32] Change `response.output` only to rebuild +the previously published fields from the new response, so saved scenarios keep their mappings: + +- Prefer built-in IML in `response.output`; custom IML functions are not available by default + ([IML functions](iml-functions.md)). Apply the same mapping to nested records that carry the same shape. +- Rebuild only what the new response can supply. Say in help or the interface which old fields can no + longer be filled, rather than inventing values. +- Exposing a new field as well is additive; dropping or retyping a field the interface declares is not. +- Test the new shape, the old shape (left unchanged), nested records, and `null` or missing input. + +### Deprecate in place + +Removing or changing a select option, removing a parameter, or replacing a connection can break saved +scenarios.[32] Keep the old element working and make its status visible at the level where it changes: + +- **Select option:** keep the option and its `value`; add `(deprecated)` to the label and put a `warning` + banner in its `nested` parameters that names the replacement. No option-level deprecation attribute is + documented, so this label-and-banner form is an inferred pattern. +- **Parameter:** move it to advanced, add `[Deprecated]` to the label and help that names the replacement; + add a banner when users must notice it.[32] Raise a clear error for it on the app side only when the + provider already refuses the parameter.[32] +- **Module:** label it `Module name (deprecated)` + ([module labels](https://developers.make.com/custom-apps-documentation/best-practices/naming-conventions/modules/module-labels.md)), + say in the description what replaces it and that it is kept for existing scenarios, and hide it so new + scenarios pick the replacement; hidden modules keep running.[6] To stop a module entirely after the + announced removal, make it fail with a message that points to the replacement rather than deleting it.[32] + The modules API also has a deprecate/undeprecate operation;[39] its effect on the editor is not described + there, so keep the label, description and visibility steps. +- **Connection:** rename it with `(deprecated)`, add the replacement, and in every module, RPC and webhook + that used it attach the new connection first and the deprecated one as the alternative.[32] + +Users then see what to migrate to, while scenarios built on the old option, parameter, module or connection +keep running until they move or the announced shutdown takes effect. + ## 5. Apply section updates without losing unrelated configuration The public API exposes section setters, not an implied element-level merge.[38][39] diff --git a/skills/make-custom-apps/references/modules-and-pagination.md b/skills/make-custom-apps/references/modules-and-pagination.md index a1d2a32..2c86a22 100644 --- a/skills/make-custom-apps/references/modules-and-pagination.md +++ b/skills/make-custom-apps/references/modules-and-pagination.md @@ -66,6 +66,41 @@ Approval impact follows [Approval gating](review-and-qa.md#2a-approval-gating): Source: [Pagination specification and limits](https://developers.make.com/custom-apps-documentation/component-blocks/api/pagination.md). +### Reads that claim items take their batch size from the Limit + +For an ordinary read, a fixed provider page size with `response.limit` is correct: records +beyond the Limit are simply not emitted, and the search best practice asks for the largest +page size. Sending a smaller page for a small Limit is an optional optimisation, never a +finding; if you do it, derive the offset step from the same expression as the page size. + +A read that changes provider state is different: receiving from a queue, claiming or +leasing items, or marking them as read. `response.limit` trims the bundles only after the +provider has handed the items out, so a batch larger than the Limit hides the extra items +until a timeout, or consumes them, without any bundle carrying them. Send the smaller of the +Limit and the documented maximum as the batch size, for example +`{{min(ifempty(parameters.limit, 10), 10)}}` for a maximum of 10. Keep the `ifempty` +fallback, because a search Limit may be left empty to return everything. + +Such a read often pages by re-sending the identical request, each call returning the next +items. A pagination block with nothing that changes per page is valid only for such a read; +on any other endpoint it fetches the first page again. When a claiming read pages, every +call claims a full batch, so the last one can claim more than the Limit leaves room for. +Either cap the Limit at the provider maximum and send one request, or size each later call by +the items still missing (count the items received so far in `response.temp`). + +### Leave the Limit stop to `response.limit` + +Do not re-implement the Limit inside `pagination.condition`: Make already stops paging +once `response.limit` items are collected. A condition such as +`{{pagination.page * 50 < parameters.limit}}` only adds risk, because `pagination.page` is +already the upcoming page, so it stops one page early (a Limit of 100 returns 50 records). +The same slip against a provider record total, `{{pagination.page * 50 < body.total}}`, +skips the last page; the records already requested are `(pagination.page - 1) * 50`. A page +size that appears only in the condition, and is not sent in the request, also depends on the +provider's default page size staying the same. Use the condition for the provider's own +signal (cursor, has-more flag, total), and test Limits of exactly one page, one page plus +one record, and two full pages. + ## Page-number pagination **`pagination.page` starts at 1 and advances automatically. After the first request, @@ -123,6 +158,62 @@ pagination endpoint can require a different method or body; inspect it explicitl Source: [Pagination patterns and merging](https://developers.make.com/custom-apps-documentation/component-blocks/api/pagination.md). +### Cursor or next link in a response header + +Some providers return the continuation in a response header instead of the body. +`headers` is available to the pagination `condition` and to the override fields, like +`body`. Read the header name in lower case, as it appears in a logged response, not in the +provider's capitalisation such as `headers.Link`. A hyphenated name needs backticks or +`get()`, because `{{headers.x-next-cursor}}` is evaluated as a subtraction. + +~~~json +{"pagination": { + "qs": {"after": "{{headers.`x-next-cursor`}}"}, + "condition": "{{headers.`x-next-cursor`}}" +}} +~~~ + +For a `Link` header, follow only the URL of the `rel="next"` entry, and let the condition +and the URL test the same relation: + +~~~json +{"pagination": { + "url": "{{replace(headers.link, '/^.*<([^>]+)>;\\s*rel=\"next\".*$/', '$1')}}", + "condition": "{{contains(headers.link, 'rel=\"next\"')}}" +}} +~~~ + +A bare `contains(headers.link, 'next')` is also true when the word only appears inside +another link's URL, and `replace()` returns the whole header unchanged when its pattern does +not match, so the module then requests the header text as a URL. A custom function that +returns the next URL or nothing, used for both fields, avoids the mismatch. The next-URL +rules above (query merging, allowed destination hosts, retained credentials) still apply. + +### Lookups by a list of IDs + +An ID filter limits which records match; it does not establish that the endpoint is +unpaginated. Check the provider's pagination contract even when the user supplies every ID. +For example, the [WordPress posts API](https://developer.wordpress.org/rest-api/reference/posts/#arguments) +accepts an `include` ID filter alongside `page` and `per_page` (default `10`). Preserve +pagination when that contract requires it to retrieve all matching records. + +For a provider-documented unpaginated batch-get endpoint, declare its documented per-call ID +cap on the input array and state it in the help. On a module that is already released, add the bound only where +the provider already rejects a longer list; where it silently drops IDs, state the cap in the +help and treat a new bound as a compatibility change ([limits the help text already states](parameters-and-rpcs.md#limits-the-help-text-already-states)): + +~~~json +{"name": "ids", "type": "array", "label": "IDs", "spec": {"type": "text", "label": "ID"}, + "validate": {"maxItems": 25}, "help": "Up to 25 IDs per run."} +~~~ + +Pagination does not lift that batch-get input cap. Do not ask for a `pagination` block on a +provider-documented unpaginated endpoint. +An existing cursor block there stops after the first call only when its `condition` tests the +cursor; without one it re-sends the same IDs and repeats their records until the Limit or the +pagination request cap stops it. Either way it suggests that the module handles more IDs than +one call accepts. + ## Universal and multi-request boundaries A universal module is a deliberate coverage fallback, not proof of endpoint-specific diff --git a/skills/make-custom-apps/references/parameters-and-rpcs.md b/skills/make-custom-apps/references/parameters-and-rpcs.md index b3e978f..9de5f5f 100644 --- a/skills/make-custom-apps/references/parameters-and-rpcs.md +++ b/skills/make-custom-apps/references/parameters-and-rpcs.md @@ -67,6 +67,25 @@ Sources: [Text](https://developers.make.com/custom-apps-documentation/block-elem [Number](https://developers.make.com/custom-apps-documentation/block-elements/parameters/number.md), [Integer and Uinteger](https://developers.make.com/custom-apps-documentation/block-elements/parameters/integer-uinteger.md). +### Limits the help text already states + +When the provider documents a count or a range and the help text repeats it ("at least 5 +items", "1 to 25", "up to 100 entries"), also put it in `validate`: `minItems`/`maxItems` on +an array or a `multiple` select, `min`/`max` on a number, `max` on a text length. The editor +then rejects a typed value while the scenario is built, instead of the provider rejecting the +run later with a vaguer error. Keep the help text, because a mapped value is only known at run +time, and keep any `default` inside the declared bounds. Only limits the provider documents +belong here; this is not a reason to invent constraints. A missing `validate` next to accurate +help text is advisory. On a module that is already released, a new bound tightens validation: +add it only where the provider already rejects values outside it, so that no saved scenario +that works today starts failing (see +[compatibility evidence](../examples/current-knowledge/guides/compatibility-evidence.md)). + +Sources: [Array](https://developers.make.com/custom-apps-documentation/block-elements/parameters/array.md), +[Number](https://developers.make.com/custom-apps-documentation/block-elements/parameters/number.md), +[Text](https://developers.make.com/custom-apps-documentation/block-elements/parameters/text.md), +[Select: multiple choice with validation](https://developers.make.com/custom-apps-documentation/block-elements/parameters/select.md). + ## Collections, arrays, and intentional empty values Define a collection's `spec` as an array of named fields. For an array of primitive @@ -90,6 +109,79 @@ Sources: [Collection](https://developers.make.com/custom-apps-documentation/bloc [Select](https://developers.make.com/custom-apps-documentation/block-elements/parameters/select.md), [Handling empty inputs](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/processing-of-input-parameters.md#handling-arrays-nulls-and-empty-strings). +### Filter parameters and built queries + +For a search whose provider accepts a query expression, Make's documented pattern offers a +built filter and a free query side by side: a required `mappable: false` select (`Search by`) +whose options nest either a `filter` parameter or a `Custom query` text field, and a request +that picks one, for example +`"filter": "{{if(parameters.searchBy === 'filter', buildQuery(parameters.filter), parameters.query)}}"`. + +- **`type: "filter"`.** `options.store` (an array or an `rpc://` reference) lists the fields + (left operands). `options.operators` uses the grouped-select shape: group operators by data + type instead of offering one list for every type. `options.logic` limits the form to `and`, + `or` or `both`. +- **Its value** is an array of OR groups; each group is an array of AND conditions + `{"a": field, "o": operator, "b": value}`, and `b` is absent for operators that take no + value. Convert it to the provider's syntax in a custom IML function, and test an empty + filter, an empty group and a value-less operator. +- **Custom query help** states the query format, gives a working example and links the + provider's query documentation. +- **Quote and escape every user value the app writes into an expression.** This covers filter + values, a search button's search text and a selected name placed into a provider filter, + query or search string; follow the provider's grammar as described in + [User values inside provider query languages](requests-and-responses.md#user-values-inside-provider-query-languages). + A custom query is the user's own expression and is sent as written; do not escape it. Say in + the help whether the search matches exactly or by substring, because an exact (`eq`) match + returns nothing for a partial value. A request that valid input breaks is a functional defect + to fix; the help wording is advice. + +Sources: [Filter](https://developers.make.com/custom-apps-documentation/block-elements/parameters/filter.md), +[Custom query and filter options](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters.md#support-for-custom-query-and-filter-options). + +### Alternative inputs behind one select + +When an operation accepts one of several input forms (file data or a reference to a stored +file, a key/value list or raw JSON, a list choice or a typed ID), use one select whose options +each carry their own `nested` fields. Only the chosen option's fields are shown, so the user +can neither fill both forms nor send neither. + +~~~json +{ + "name": "source", "type": "select", "label": "Source", "required": true, "mappable": false, + "options": [ + {"label": "File data", "value": "data", "nested": [ + {"name": "fileName", "type": "filename", "label": "File name", "semantic": "file:name", "required": true}, + {"name": "data", "type": "buffer", "label": "Data", "semantic": "file:data", "required": true}]}, + {"label": "Stored file", "value": "stored", "nested": [ + {"name": "fileKey", "type": "text", "label": "File key", "required": true}]} + ] +} +~~~ + +- Make the switch `mappable: false`. It decides which fields appear, and with the Map toggle + on the nested fields disappear. `required: true` inside a branch applies only while that + branch is chosen. +- Let the request read the switch to choose the branch, for example + `"fileKey": "{{if(parameters.source === 'stored', parameters.fileKey, undefined)}}"`, and + keep the switch itself out of the provider payload. +- Branches may reuse one field `name` with different types (a key/value array in one, JSON + text in the other). Convert that value according to the switch, never by guessing from the + value's shape, and test each branch. +- A switch inside an array item's `spec` has a value per item, so the request or helper must + convert and remove it per item. Declare a switch once, at the level the choice belongs to; + a second copy at another level is an input nothing reads. +- When a field offers several ways to find one record, the documented label for the switch + is `[Item] search method`, with options such as Select from list, Search by keyword or + Enter manually. +- The form shape is advisory. A request that sends both branches, or converts a branch value + wrongly, is a functional defect. In a released module, check what saved scenarios map + before turning mapping off on an existing switch or moving fields into branches (see Form + quality). + +Sources: [Select: nested fields for specific options](https://developers.make.com/custom-apps-documentation/block-elements/parameters/select.md), +[Mappable: false and search methods](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters.md). + ## Form quality (UX guidance, not schema rules) These points make a form readable. They are recommendations from the public @@ -137,6 +229,31 @@ Guides: [labels and visibility](../examples/current-knowledge/guides/labels-visi [selectors and mode](../examples/current-knowledge/guides/selectors-mode.md), [interfaces and required flags](../examples/current-knowledge/guides/interfaces-required.md). +### Banners + +A `banner` parameter shows a message in the form: `text`, an optional `title`, and a +`theme` of `info`, `warning` or `danger`. The recommended length is 50 to 300 characters. A +banner has no `name` and sends no value. + +~~~json +{"type": "banner", "theme": "info", "text": "Use at most one filter: Status, Owner or Tag. The provider rejects a request that combines them."} +~~~ + +- Use it for what one field's help cannot carry: a rule across fields (use at most one of + these filters, give either A or B), a cost, quota or rate note, the consequence of a mode, + or the setup steps for a webhook that is not attached. Keep each field's own help as well. +- A fields RPC can return a banner in a conditional step, so the message appears only when + it applies, for example for one selected option (see + [notices from an RPC](../examples/current-knowledge/guides/dynamic-data-and-files.md#notices-and-connection-specific-help-from-an-rpc)). +- Prefer a banner to a field of type `html` whose label carries inline markup and fixed + colors. `html` is in neither the documented parameter types nor the editor schema's `type` + enum, so schema validation warns on it. Such fields are seen in approved apps, + so replacing one is advisory, not a defect to fix. +- A missing banner, or one worded differently, is advisory. + +Sources: [Messages (banners)](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters.md#messages-banners), +[Instructions for a webhook that is not attached](https://developers.make.com/custom-apps-documentation/app-components/webhooks/dedicated/not-attached.md). + ## Dynamic options RPCs RPCs execute during scenario configuration, not as substitutes for action execution. @@ -168,6 +285,85 @@ Sources: [RPC connection contract](https://developers.make.com/custom-apps-docum [Dynamic options](https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-options-rpc.md), [RPC usability and limits](https://developers.make.com/custom-apps-documentation/best-practices/remote-procedure-calls.md). +### Search buttons (ID finder) + +A field can carry an `rpc` object: a button opens a small form, the RPC searches the +provider with that form's values, and the chosen result's `value` fills the field. + +~~~json +{ + "name": "recordId", "type": "text", "label": "Record ID", "required": true, + "rpc": { + "label": "ID finder", + "url": "rpc://searchRecords", + "parameters": [ + {"type": "banner", "theme": "info", "text": "Only a limited number of results can be shown. If you don't see the item you're looking for, try more specific search criteria."}, + {"name": "keywords", "type": "text", "label": "Record keywords", "required": true} + ] + } +} +~~~ + +The RPC reads the form as `parameters.` and returns `{label, value}` like an options RPC: + +~~~json +{ + "url": "/records/search", + "qs": {"q": "{{parameters.keywords}}"}, + "response": {"limit": 100, "iterate": "{{body.items}}", "output": {"label": "{{item.name}} ({{item.id}})", "value": "{{item.id}}"}} +} +~~~ + +- The field stays an ordinary mappable field with its own type, `required` and help; mapping + works without the finder. +- Label the button `ID finder` (`Finder` when the field is not an ID, such as a path). Label a + keyword input `[Item] keywords` and keep the info banner. For an exact-match input, use the + item's own name as the label, add the hint "Must be the exact [item].", and leave the banner + out. +- Do not mark a result `default: true`; that is for selects. After selection the field shows + the value, not the label, so a result label must identify the record on its own (a name plus + a distinguishing detail, such as `{{item.name}} ({{item.id}})`). List results alphabetically + when the provider can sort them. +- Leave an empty optional filter of the search form out of the request + (`ifempty(parameters.status, undefined)`), as the documented advanced search example does; + it is a search input, not an update that may need to clear a value. Keep the RPC inside its + budget ([RPC page budgets](../examples/current-knowledge/guides/rpc-page-budgets.md)); a more + specific term finds what the budget cuts off. +- `mode` belongs to selects. A text field with a search button already takes a typed or + mapped value, so a missing `mode: "edit"` on it is not a finding. Its `rpc://` name must + still resolve, and the RPC must share the module's connection. +- When the same finder form is copied into several modules, review the copies together; + flags such as `mappable` drift between copies. + +Sources: [Search button](https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-options-rpc.md#search-button), +[ID finder](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/mappable-parameters.md#id-finder). + +### Grouped options + +For a long list with natural sections (supported and preview choices, item families), set +`"grouped": true` on the select and let the RPC return groups instead of a flat list: +`[{"label": "Group", "options": [{"label": "Item", "value": "item-1"}]}]`. The flag is what makes +the editor read the group objects; a select that receives flat `{label, value}` pairs does not set +it. The Select page shows the grouped shape with hand-written options only, so confirm in the form +that groups an RPC returns render. Keep every `value` the full identifier, unique across groups, and +put extra detail only in the label. Leave out empty groups, and give an item that matches no +grouping rule a fallback group rather than dropping it or letting the helper throw. + +Source: [Select: grouped](https://developers.make.com/custom-apps-documentation/block-elements/parameters/select.md#grouped). + +### Option and finder RPCs only read + +An RPC runs while a person configures the module, each time its field loads or is refreshed. +Classify its request by effect, as for module requests: an options, fields or finder RPC +must not call an endpoint that receives, leases, claims, marks as read or otherwise changes +provider state, because opening a dropdown would then hide or alter live data. Its values +must also be identifiers a user can save; a short-lived token issued per delivery (a receipt +handle, a lease ID) is usually no longer valid when the scenario runs. Offer a mappable text +field instead, with help naming the earlier module output to map. Fix a state-changing RPC; +it is not a style point. + +Source: [RPCs run while the user builds the scenario](https://developers.make.com/custom-apps-documentation/app-components/rpcs.md). + ## Dependent options, fields, and interfaces - Use `options.store` together with `options.nested` for dependent selects. @@ -190,6 +386,88 @@ Sources: [Dynamic fields](https://developers.make.com/custom-apps-documentation/ [Dynamic interface](https://developers.make.com/custom-apps-documentation/component-blocks/interface.md#dynamic-interface-using-rpc), [Dynamic samples](https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-sample-rpc.md). +### Fixed arguments in an `rpc://` reference + +The documented RPC query parameters look like a query string: +`"options": "rpc://listItems?type=contact&active=true"`. Each argument reaches the RPC as +`parameters.`, next to the inherited module parameters. Repeat a key (`?kind=a&kind=b`) +to pass an array, which the RPC declares as an `array` parameter. One RPC can then serve +several fields with different fixed context instead of near-identical copies that drift +apart. + +- The RPC must read every argument it is given. An unread `?type=chat` filters nothing while + readers assume it does; use it or remove it. +- Every value a caller passes needs a matching branch or filter in the RPC; an unknown value + must not fall through to an empty or wrong list. +- Do not test an argument for truthiness. The documentation does not say whether + `active=false` arrives as the text `'false'`, which is truthy, or as a boolean. Forward it + as the documented example does, or prefer arguments whose values are compared rather than + tested, such as `type=contact`. +- Give arguments names that differ from the module's own parameter names: both arrive as + `parameters.`, and which value wins is not documented. +- An RPC that reads a parameter no module declares may be fed by such an argument. Check the + callers' `rpc://` references before reporting it as an undeclared input. + +Source: [Send query to RPC and send array to RPC](https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-options-rpc.md#send-query-to-rpc). + +### Condition-aware RPCs: steps with `condition` + +The condition-aware RPC named under Form quality is an RPC whose communication is an array +of steps, each with its own `condition`; a step whose condition is false is skipped. Use it +for a fields RPC that returns a different field group per value of a sibling select, for an +RPC that first reads facts about the selected item and then decides which field to offer, +and for a lookup that must not run with empty input. Values pass between steps through +`response.temp`. + +~~~json +[ + { + "condition": "{{parameters.itemId}}", + "url": "/items/{{parameters.itemId}}", + "response": {"temp": {"needsProfile": "{{body.mode === 'profile'}}"}, "output": null} + }, + { + "condition": "{{temp.needsProfile}}", + "response": {"output": [{"name": "profileId", "type": "select", "label": "Profile", "required": true, "options": "rpc://listProfiles"}]} + }, + { + "condition": "{{!temp.needsProfile}}", + "response": {"output": []} + } +] +~~~ + +- Make the conditions of the steps that produce the result mutually exclusive and together + cover every case, as the documented request-less example does with a condition and its + negation. Where no step applies, the user sees nothing and gets no error. +- A step without `output` returns the response body by default, so a step that only fills + `response.temp` still produces a result, and a later step that is skipped or returns `null` + does not replace it. Give a gathering step `"output": null` (a deliberate exception to the + Output page's advice to define `output` only in the final step, so its body cannot become the + result) and the no-match case an explicit result: a last step with the negated condition (an + empty array means no fields or no options), or the documented `condition` object, whose + `default` is the result when the condition is false. +- Guard a request that depends on an earlier step's result, for example + `"condition": "{{length(temp.ids) > 0}}"` before a batch lookup of those IDs, so an empty + first result gives an empty list instead of a provider error. Keep the batch within the + provider's ID count and URL length limits. Every step that sends a request counts toward + the RPC's recommended budget of about three requests (see + [RPC page budgets](../examples/current-knowledge/guides/rpc-page-budgets.md)). +- Branch on an explicit signal from the provider (a capability flag or a type field), not on + a substring of a name or label: a new or renamed value silently gets the wrong branch. +- A field `name` built by an expression or helper must be defined in every state, including + an empty parent selection. +- Some apps detect a mapped parent with `contains(parameters.parentId, '{{')`, assuming the + RPC then receives the unresolved mapping text, and return a generic input. This is a + technique seen in approved apps, not a documented signal: do not report it as wrong where both the + choose path and the map path work, and do not add it as a universal guard (see the + selectors guide). + +Sources: [condition](https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests.md#condition), +[Request-less communication](https://developers.make.com/custom-apps-documentation/component-blocks/api/request-less-communication.md), +[Multiple requests](https://developers.make.com/custom-apps-documentation/component-blocks/api/multiple-requests.md), +[Dynamic fields](https://developers.make.com/custom-apps-documentation/app-components/rpcs/dynamic-fields-rpc.md). + ## Current-knowledge guides Open the guide for the question at hand; each carries sources, applicability, exceptions and @@ -219,3 +497,11 @@ authored synthetic correct/incorrect fixtures (static teaching material, not run optional fields, and file semantics. A sample is not proof of all possible fields. - Keep fixture data synthetic or sanitized. Report UI/RPC execution separately from static JSON checks; an upload alone does not prove the selector opens. +- Check that every option label is readable and never blank. Free text (a description, a + message body) can be empty, very long or multiline, so fall back to another field or the ID + (`{{ifempty(item.title, item.id)}}`) and keep the stable ID as `value`. Do not build a label + from a fixed array position, such as the second member of a list, unless the provider + guarantees that order. +- Check every branch of a helper that builds options, including its not-found and empty + branches: each returns `{label, value}` objects, never bare strings, and its test asserts + that shape. diff --git a/skills/make-custom-apps/references/requests-and-responses.md b/skills/make-custom-apps/references/requests-and-responses.md index 63a5995..6f76616 100644 --- a/skills/make-custom-apps/references/requests-and-responses.md +++ b/skills/make-custom-apps/references/requests-and-responses.md @@ -25,6 +25,156 @@ Approval impact for any request-contract finding follows [Approval gating](revie Sources: [Request directives](https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests.md), [Special query encoding](https://developers.make.com/custom-apps-documentation/best-practices/input-parameters/processing-of-input-parameters.md#special-case-query-string-parameters-in-the-url). +### Array fields: match the shape of the input + +A literal array around a single-value input is how one value reaches an array field: +`"ids": ["{{parameters.id}}"]`. Around a `multiple: true` select or an `array` input it nests +the user's array inside another one and sends `[["a", "b"]]`; pass such a parameter directly +(`"ids": "{{parameters.ids}}"`). Check every literal `[...]` in a body against the +multiplicity of what it wraps, and compare sibling components (attach and update, create and +update) that send the same field. + +### Key/value rows for open maps + +For a provider field that is an open map (custom attributes, metadata, template variables), +offer an array of key/value rows and convert it with `toCollection(rows, 'key', 'value')`; +the GraphQL universal module example converts its variables the same way. Combine it with +whole-parameter mapping: spread the other parameters first, then write the converted field +after the spread so it is the value that is sent. + +```json +{ + "body": { + "{{...}}": "{{omit(parameters, 'attributes')}}", + "attributes": "{{if(parameters.attributes, toCollection(parameters.attributes, 'key', 'value'), undefined)}}" + } +} +``` + +`toCollection()` returns `{}` for a missing value, and on Apps platform version 2 an array +input the user left blank is missing, so without the guard a blank field is sent as an empty +map. Test presence, not length: an erased input arrives as `[]`, still passes the test and is +sent as `{}`, so a user can clear the map where the provider documents that. A guard such as +`if(length(...) > 0, ...)` would make clearing impossible, which the input-processing best +practices list as a bad practice. Use the row field names the parameter actually declares +(`key`/`value`, `title`/`value`, `name`/`value`). + +### Optional groups and empty-collection cleanup + +When every field of a collection is left empty, Make still sends the collection as `{}` +([Processing of empty values](https://developers.make.com/custom-apps-documentation/other/processing-of-empty-values.md)), +and a parent written literally in the request (`"filters": {"a": ..., "b": ...}`) is sent as +`"filters": {}` when every child resolves empty. Some APIs reject an empty object or read it +differently from an absent group. Clean the whole group in one expression instead of cleaning +each child: for a collection parameter, use the `length(keys(...)) > 0` guard in +[outputs, empty values and updates](../examples/current-knowledge/guides/outputs-empty-values-updates.md#optional-collections-send-them-only-when-filled); +for a parent built from separate inputs, use a custom function (where custom IML functions are +enabled) that returns `undefined` when every child is empty. Test the all-empty case, not only a +filled form. + +Check a copied removal helper before relying on it: the documented example sends an array of +plain values (`["a", "b"]`, a multiple select) as `[null, null]`, and still sends an erased +collection such as `{"street": null}` as `{}`. The branch-by-branch checks and a corrected +helper are in +[outputs, empty values and updates](../examples/current-knowledge/guides/outputs-empty-values-updates.md#recursive-cleanup-helpers-check-every-branch). +Like any removal helper, it does not belong where an empty value must clear a field. + +Source: [Removal of empty collections and nulls](https://developers.make.com/custom-apps-documentation/app-components/iml-functions/removal-of-empty-collections-and-nulls.md). + +### A computed method must always resolve + +`method` accepts an IML expression (the request directives page shows +`{{if(parameters.create, 'POST', 'PUT')}}`), so one module can choose `POST`, `PATCH` or +`PUT` from a select. The expression must yield a method for every value the field can hold, +including an empty one. A `switch()` without a final fallback returns nothing for an +unmatched value (for example a select default `create` against option values `Create`), and +the request then goes out with the default `GET`, which drops the body without any error. + +```json +{ + "method": "{{switch(parameters.action, 'create', 'POST', 'update', 'PATCH', 'upsert', 'PUT', 'POST')}}", + "body": {"{{...}}": "{{omit(parameters, 'action', 'id')}}"} +} +``` + +Keep the select default identical to one option value, end `switch()` with a fallback, +remove the selector and path-only fields from the body, and say in the help what each choice +does. + +### Path segments when `encodeUrl` is off + +`encodeUrl: false` hands URL encoding to the module: Make no longer encodes the path. Pass +every interpolated path segment through `encodeURL()`, not only the one that prompted the +change. Do not hand-replace a single character (`:` to `%3A`): `/`, `?`, `#`, `%` and spaces +in a mapped ID stay raw, so a slash changes the route and a `?` or `#` starts a query or a +fragment. + +```json +{"url": "/objects/{{encodeURL(parameters.type)}}/{{encodeURL(parameters.key)}}", "encodeUrl": false} +``` + +This is about path segments. Keep query values in `qs`: with `encodeUrl: false`, Make +decodes percent-encoded characters in a query string written into the `url`, so a +hand-encoded query there needs the default `true` (see the `encodeUrl` warning in the +request directives). Test IDs that contain the characters above. + +### User values inside provider query languages + +Some APIs take a filter, search or key expression in their own syntax: a `$filter`-style +query parameter, a search string, a key predicate in the path. When a module or helper +builds that expression from mapped values, treat each value as a literal of that language: + +- escape its quote character the way the provider documents; languages that quote text with + single quotes usually double an embedded one (`O'Brien` becomes `'O''Brien'`); +- check numbers and dates before formatting them in: a non-number becomes `NaN`, and an + unparsable date throws inside the helper; +- take field and operator names from a fixed list or your own RPC, never from free text; +- send a finished query expression through `qs` so Make encodes it. + +```js +function quoteLiteral(value) { + return "'" + String(value).replace(/'/g, "''") + "'"; +} +// `${field} eq ${quoteLiteral(value)}` +``` + +An unescaped quote turns a valid input, such as a surname, into a 400 or a different filter. +Give the helper tests with quotes, empty values, numbers and dates. + +### GraphQL operations in ordinary modules + +Keep the operation text fixed and pass every user value through `variables`, declared with +its GraphQL type in the operation signature, as the GraphQL universal module does. Splicing +mapped values into the query text breaks on quotes, backslashes, braces and newlines, lets a +mapped value change the operation, and needs string fragments for optional arguments. With +variables, an optional value left empty is simply omitted and no escaping helper is needed. + +```json +{ + "url": "/graphql", + "method": "POST", + "body": { + "query": "mutation ($id: ID!, $name: String!, $note: String) { renameItem(id: $id, name: $name, note: $note) { id name } }", + "variables": { + "id": "{{parameters.itemId}}", + "name": "{{parameters.name}}", + "note": "{{parameters.note}}" + } + } +} +``` + +Avoid `"query": "mutation { renameItem(id: {{parameters.itemId}}, name: \"{{parameters.name}}\") { id } }"`. + +When the provider's schema expects a JSON-encoded string for a variable (check its scalar +documentation), that is the JSON-string-inside-JSON case above: serialize an object once and +pass an already encoded string unchanged, so it is not encoded twice. When part of the +document must be generated (a field selection chosen in the module), build it only from names +your own RPC returned, never from free text, and test the helper with quotes, backslashes and +newlines. Errors inside HTTP 200 responses still need `valid` (see below). + +Source: [GraphQL universal module: query, operation name and variables](https://developers.make.com/custom-apps-documentation/app-components/modules/universal-module/graphql.md). + ## Parse before shaping output `response.type` controls parsing, independently of request `type`. Automatic parsing @@ -78,6 +228,56 @@ Sources: [Valid responses](https://developers.make.com/custom-apps-documentation [Error schema, status defaults, and precedence](https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/error.md), [HTTP errors cannot be evaluated as success](https://developers.make.com/custom-apps-documentation/app-components/base/error-handling.md). +### Messages from a list of provider errors + +When the provider returns a list of field errors next to, or instead of, one message, join +the list and fall back to the top-level message. The user then sees every failing field, and +an empty or missing list still leaves a message. Put the list in the per-status entries whose +body the provider documents as JSON (often 400 and 422). `map()` accepts only an array or +nothing, so in the generic message a text or HTML gateway body, or a single error object, +replaces the status with a function error. + +```json +{ + "response": { + "error": { + "message": "[{{statusCode}}] {{body.error.message}}", + "400": { + "message": "[{{statusCode}}] {{ifempty(join(map(body.error.details, 'message'), '; '), body.error.message)}}" + } + } + } +} +``` + +Map the property that holds the readable text (`message`, `detail`), keep the status prefix, +and leave credentials and request echoes out. More message shapes are in +[errors and rate limits](../examples/current-knowledge/guides/errors-and-rate-limits.md#building-the-message-from-the-providers-error-shape). + +### A lookup that finds nothing + +A Get module that reads one record through a list, filter, by-IDs or parent query +(`body.items[1]`, `body.data.parents[1].children`) usually receives HTTP 200 with an empty +list when the ID is unknown or deleted. The module then succeeds with an empty or almost +empty bundle, and the scenario continues with blank values. Decide it explicitly: mark the +response invalid with a not-found message, or state in the help that an empty result means +"not found". + +```json +{ + "response": { + "valid": { + "condition": "{{length(body.items) > 0}}", + "message": "No record found for ID {{parameters.id}}." + }, + "output": "{{body.items[1]}}" + } +} +``` + +This is a design decision to make visible, not by itself a rejection reason +(see [Approval gating](review-and-qa.md#2a-approval-gating)). + ## Keep output, temporary state, and wrappers distinct - `response.iterate` selects an array; `response.output` shapes each selected `item`. @@ -93,6 +293,42 @@ Sources: [Valid responses](https://developers.make.com/custom-apps-documentation Sources: [Output and wrapper](https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/output.md), [Response temp](https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/temp.md). +### Values from response headers + +Besides `body` and `statusCode`, the response context has `headers`: the response headers +of the last request. Some values exist only there: the ID or location of a resource whose +create call answers with an empty body, the file name of a download +(`Content-Disposition`), and next-page cursors or links. Read them by their lower-case name, +with backticks around a name that contains special characters +(``{{headers.`x-request-id`}}``, `{{headers.location}}`). + +```json +{ + "url": "/records", + "method": "POST", + "body": "{{parameters}}", + "response": { + "temp": {"newId": "{{last(split(headers.location, '/'))}}"}, + "output": {"id": "{{temp.newId}}", "location": "{{headers.location}}"} + } +} +``` + +In a request array each later response replaces `headers`, so copy a value into +`response.temp` in the step that received it. Give header-derived values a fallback (a +download without `Content-Disposition` still needs a file name), and declare every value you +output in the interface. + +Source: [Action module IML variables](https://developers.make.com/custom-apps-documentation/app-components/modules/action/components.md). + +### Temporary values merge, they do not replace + +See [requests, files and multi-step](../examples/current-knowledge/guides/requests-files-multistep.md#how-temp-merges-arrays-and-objects) +— how `temp` merges arrays position by position and collections key by key, and why each +processing stage and loop control needs its own key and an explicit end value. + +Source: [Response temp](https://developers.make.com/custom-apps-documentation/component-blocks/api/handling-responses/temp.md). + ## Multiple requests and safe updates Use an array of request specifications for a sequential chain. Persist only required @@ -151,6 +387,44 @@ and [outputs, empty values and updates](../examples/current-knowledge/guides/out Guides for the neighbouring questions: default 429 and 5xx handling, `valid` and per-status errors in [errors and rate limits](../examples/current-knowledge/guides/errors-and-rate-limits.md). +### Steps without a request + +An element of the request array that omits `url` sends nothing (request-less communication). +Its request directives (`method`, `qs`, `headers`, `body`, `type`) are ignored, while its +`condition`, `temp`, `valid` and `output` still run. The step has no response of its own, so +read `temp` there, not `body`: copy what it needs into `response.temp` in the step that +received it. Put the failure text in `valid.message`. The request-less page says `valid` and +`error` lose their value in this mode, and a `response.error` message is not applied to a step +that sent no request. The batch-actions asynchronous example closes its chain with such a step. +Use such a step to: + +- fail early with a clear message when an input combination cannot work; +- turn a status collected by earlier steps into a success or a clear error; +- emit the output of the branch that ran: give each branch its own closing step with its own + `condition`, instead of relying on an earlier output surviving a skipped step. + +```json +[ + {"url": "/jobs", "method": "POST", "body": "{{parameters}}", "response": {"temp": {"job": "{{body}}"}}}, + { + "response": { + "valid": { + "condition": "{{temp.job.status != 'rejected'}}", + "message": "Job {{temp.job.id}} was rejected: {{temp.job.reason}}" + }, + "output": "{{temp.job}}" + } + } +] +``` + +Omit `url` entirely: a `url` expression that resolves to an empty value is not the same and +still sends a request. Keep the closing steps' conditions mutually exclusive so exactly one +of them produces the output. + +Sources: [Request-less communication](https://developers.make.com/custom-apps-documentation/component-blocks/api/request-less-communication.md), +[Asynchronous process](https://developers.make.com/custom-apps-documentation/best-practices/modules/batch-actions.md#asynchronous-process). + ## Bounded asynchronous polling with repeat Start a job once, retain its ID, then repeat a read-only status request. @@ -177,6 +451,48 @@ Never blindly repeat a non-idempotent creation request to wait for its completio Source: [Repeat, delay, limit, and temporary state](https://developers.make.com/custom-apps-documentation/component-blocks/api/making-requests.md#repeat). +### Optional waiting, user-set bounds and partial results + +- **Optional waiting.** When a boolean input chooses between "start and return the job ID" + and "wait for the result", put a `condition` on the polling step and close each branch + with its own request-less step (see "Steps without a request"), with the same job-ID key + and status field in both outputs. Say in the help that waiting is bounded and that a + status module or a webhook fits long jobs. +- **A bound the user can set.** `delay` and `limit` are not evaluated, so + `"limit": "{{parameters.maxChecks}}"` offers a setting that is ignored and can leave the loop + without a working bound. Count the checks in `temp`, copy the user's bound into `temp` too (a + `repeat.condition` reads only `temp`), test both there, keep a literal `limit` as the + ceiling, and cap the input at that ceiling (`validate.max`). +- **Check before you iterate.** A failed job usually has no result array; iterating it + returns zero bundles and no error. Check the stored status first, in a closing step whose + `valid` accepts only success and whose message names the status and the job ID. +- **Partial results.** When a batch call or a finished job answers with success but lists + unprocessed or failed items, do not report full success: return those items, or fail with + them, as the provider contract allows. Do not re-send them inside the polling loop; rate + limits stay with Make's error handling (see the error section above). + +```json +[ + {"url": "/jobs", "method": "POST", "body": "{{parameters.job}}", + "response": {"temp": {"jobId": "{{body.id}}", "accepted": "{{body}}"}}}, + {"condition": "{{parameters.wait}}", "url": "/jobs/{{temp.jobId}}", "method": "GET", + "response": {"temp": {"status": "{{body.status}}", "job": "{{body}}", "checks": "{{ifempty(temp.checks, 0) + 1}}", "maxChecks": "{{ifempty(parameters.maxChecks, 30)}}"}}, + "repeat": { + "condition": "{{(temp.status == 'queued' || temp.status == 'running') && temp.checks < temp.maxChecks}}", + "delay": 5000, + "limit": 60 + }}, + {"condition": "{{parameters.wait}}", + "response": { + "valid": {"condition": "{{temp.status == 'succeeded'}}", + "message": "Job {{temp.jobId}} has status {{ifempty(temp.status, 'unknown')}}, not succeeded."}, + "output": {"{{...}}": "{{temp.job}}", "jobId": "{{temp.jobId}}"} + }}, + {"condition": "{{!parameters.wait}}", + "response": {"output": {"{{...}}": "{{temp.accepted}}", "jobId": "{{temp.jobId}}"}}} +] +``` + ## Multipart, binary, and verification For multipart uploads, accept a `buffer` field and a filename. The file part uses @@ -211,3 +527,26 @@ A syntactically valid request or uploaded definition is not evidence of successf Sources: [Multipart uploads](https://developers.make.com/custom-apps-documentation/component-blocks/api/multipart-form-data.md), [Buffer and file semantics](https://developers.make.com/custom-apps-documentation/component-blocks/api/buffer.md), [Custom CA scope](https://developers.make.com/custom-apps-documentation/other/https-custom-ca.md). + +### Raw binary uploads + +`type: "binary"` sends the buffer as the whole body. Unlike `json`, `urlencoded` and +`multipart/form-data`, it sets no Content-Type of its own, so set the one the provider +expects in the request `headers`: a fixed type when the endpoint accepts one format, a +mapped MIME-type input, or a type derived from the file extension with +`application/octet-stream` as the fallback. Keep the file name and the MIME type as separate +values, and check that a helper used in the header really returns a MIME type. A per-name +header in the request also replaces a JSON Content-Type inherited from Base. + +```json +{ + "url": "/uploads", + "method": "POST", + "type": "binary", + "headers": {"Content-Type": "{{ifempty(parameters.mimeType, 'application/octet-stream')}}"}, + "body": "{{parameters.data}}" +} +``` + +Providers that trust the header reject or mislabel a wrong type; others sniff the bytes and +hide the mistake until a stricter endpoint is used. diff --git a/skills/make-custom-apps/references/review-and-qa.md b/skills/make-custom-apps/references/review-and-qa.md index 1d4f6ef..d727d10 100644 --- a/skills/make-custom-apps/references/review-and-qa.md +++ b/skills/make-custom-apps/references/review-and-qa.md @@ -20,9 +20,10 @@ Make's public review prerequisites require functional test scenarios and recent, Use the current public rules, not internal category codes or an old app's style as universal requirements. Approval impact is decided separately in [Approval gating](#2a-approval-gating). -Report an **Error** for a demonstrated class (a) to (d) defect, **Warning** for risk or missing evidence, and -**Suggestion** for optional improvement; a demonstrated convention or quality deviation is recorded as a Warning -or Suggestion, since only class (a) to (d) defects use the Error level. Cite the applicable rule and exact component/section for each finding. +Report an **Error** for a demonstrated class (a) to (d) defect, except credential masking (a missing +`log.sanitize` path): Warning, still `blocks` and fixed; see How to record. Report a **Warning** for risk or +missing evidence, and **Suggestion** for optional improvement; a demonstrated convention or quality +deviation is recorded as a Warning or Suggestion, since only class (a) to (d) defects use the Error level. Cite the applicable rule and exact component/section for each finding. Assess each finding before deriving the overall verdict. A finding that blocks under [Approval gating](#2a-approval-gating) is fixed (approve with adjustments), including class (b) findings; only the scam reasons under Reject end in rejection; advisory findings leave the component acceptable; each finding keeps its own approvalImpact even when another finding already rejects the app. Keep recommendations and uncertainty in their evidence-based categories. Existing route-alias and optional Endpoint rules remain unchanged, as do every required execution and publication gate. @@ -82,6 +83,100 @@ For worked synthetic examples and a per-check application table, see [role application examples](../examples/current-knowledge/guides/role-application-examples.md) and [review sweeps](review-sweeps.md). +### Leftover editor-template modules + +A module created from an editor template keeps plausible defaults until each part is replaced: a +generic path such as `/users` or `/users/{{parameters.id}}`, an `iterate` of `body.users`, template +inputs (`id`, `email`, `name`, `search`, `limit`), a matching interface, and `item.created` as a +trigger date. Approved apps were seen still shipping such modules, usually hidden or labelled as not +for use, and occasionally visible under a label for an operation the request never performs. Sweep +every module, hidden ones included, and compare its label and description with its request, inputs +and interface. + +- Template comments alone prove nothing: finished modules often keep them, and the documentation's + own snippets use the same comment style. Judge the request, not the comments. +- An executable module in the intended review scope whose request does not perform the operation + its label names has a functional defect (class (a)), including a newly created hidden module. + Implement it when the provider documentation determines the operation; + otherwise report an unverified advisory finding that names the missing fact and the decision + (implement it or hide it). Do not delete a module from a released app in a review: saved + scenarios may use it, and even a hidden module still runs in them + ([labels-visibility](../examples/current-knowledge/guides/labels-visibility.md#module-distribution-visibility-not-parameterhidden)). +- Hidden status or a not-for-use label alone does not prove retirement: [new modules start + hidden](https://developers.make.com/custom-apps-documentation/create-your-first-app/test-your-app), + and [hidden modules can still execute in existing scenarios](https://developers.make.com/custom-apps-documentation/create-your-first-app/app-visibility). + Require explicit retirement evidence (such as a maintained module inventory or deprecation notes) + and evidence that the module is outside the intended review scope before leaving its template + implementation unchanged with an advisory note. Fix established defects in executable, in-scope + modules regardless of visibility. One leftover module is never a trash rejection while the rest + of the app works. +- When authoring, start from a blank module or replace every template part before the module is made + visible. Delete an unfinished module only if it was never visible in a released version. + +```json +{ "url": "/users", "method": "GET", "qs": { "search": "{{parameters.search}}" }, + "response": { "iterate": "{{body.users}}", "output": "{{item}}" } } +``` + +In a module labelled for another resource, this shape is the template, not an implementation. + +### Identifying values in samples + +Samples are part of the app definition and are shown to the app's users while they set up a module, +so a sample copied from a real run distributes whatever that run returned. Approved apps were seen +carrying account numbers inside resource URLs and resource names, personal email addresses, +phone-number chat identifiers, message or session handles and trace IDs. Check every static sample +for values that identify a real account, person or resource. + +- Replace only the identifying part with a neutral placeholder of the same type and shape: a + zero-filled account number inside an otherwise unchanged URL, an `example.com` email address or + tenant host, a short dummy handle, a fictional phone number. Keep every key, nesting level and + value type so the sample still matches the interface. This changes values only; the rule to + preserve existing samples still holds. +- A live credential, API key, access token or signed URL in a sample is a secret stored in plain + text (class (b)) and is fixed. Other identifying values are advisory with a clear fix, so replace + them (approve with adjustments). +- Not a finding: the provider's public hosts and support addresses, documented example values, and + values that are already placeholders or redacted. + +```json +{ "resourceUrl": "https://api.example.com/accounts/000000000000/items/42", + "handle": "dummy-handle", "email": "user@example.com" } +``` + +Make's review prerequisites ask that test scenarios and their logs contain no personal or sensitive +data; samples taken from those runs need the same care.[8][19] + +### Identifiers inside nested selects + +`required` belongs to each parameter; a nested child does not inherit it from its parent select. The +Select documentation's nested-RPC example marks both the parent and the nested child +`required: true`. A child that supplies an identifier for the request path needs its own flag, as +any path parameter does +([interfaces-required](../examples/current-knowledge/guides/interfaces-required.md#required-parameters)). +Otherwise the form accepts an empty value and the request goes out with an empty path segment, for +example `DELETE /items/` instead of `DELETE /items/{id}`. The provider then answers for another route, +with an error or a different operation, instead of Make's required-field validation stopping it. + +- In Get, Update, Delete and other single-record modules, trace every identifier the request always + needs to its declaration, including `nested` arrays (on the parameter, in its `options` object or + its placeholder, or on an option) and fields an RPC returns. A required parent does not cover its + child. +- Compare sibling modules: the same nested identifier marked required in Get but not in Delete is + direct evidence of the gap. +- Record it as the authoring correction that guide describes (advisory unless class (a) to (d) + applies) and add `required: true` on the child; the fix is clear, so apply it, and state the + compatibility impact in the finding, because the breaking-changes page lists changing `required` + from false to true. A saved scenario that leaves the value empty never reached the intended + record, so the flag replaces a misrouted request with Make's required-field validation. + +```json +{ "name": "parentId", "type": "select", "label": "Parent", "required": true, + "options": { "store": "rpc://listParents", "nested": [ + { "name": "id", "type": "select", "label": "Item", "options": "rpc://listItems", "required": true } + ] } } +``` + ## 2a. Approval gating This section defines `approvalImpact` and the three review outcomes. They are the reviewer's verdict on the @@ -161,6 +256,14 @@ with the wrong type; dropped 0, false or null, or missing empty-value handling; documented maximum; non-advancing pagination; wrong output container or iterate path; invalid IML or JSON; a missing binding. Re-parse and re-check every adjusted file before returning it. +Fix quality rules. + +- Evidence threshold: change an existing working mapping, output path or request only when the provider's schema or reference (not an abridged or illustrative example) or other cited evidence shows the current one is wrong. An example that omits a field is not evidence the field is absent. Otherwise keep the working code and report an advisory finding naming the doubt. +- Scope: change only the files a finding requires. Do not touch README or documentation files, hidden modules or unrelated components unless a finding is about them, and make each change's explanation describe that change. +- Prefer a minimal inline fix over a new helper. A new or changed helper function updates its test file in the same change. +- Do not add requests, polling or retries the contract does not require. Verify the runtime semantics (pagination stop, repeat, retries) before changing them. +- Prioritise functional defects. Credential masking (a missing `log.sanitize` path) is a minor fix: it is still fixed (approve with adjustments) and listed after the functional fixes, and it never displaces a functional one. A credential written to output or sent to another host is not masking and keeps its full severity. + Defect classes (a) to (d): - (a) **Established functional failure** under the applicable contract. This list is open; it includes a request @@ -177,8 +280,8 @@ Defect classes (a) to (d): and pagination on documented paged responses with no, or non-advancing, page progression. - (b) **Security or privacy**, always fixed (see the Outcome rules for what is adjusted and what is not a defect): a secret collected through a plain `text` (non-`password`) connection or install parameter; a - secret stored or logged in plain text, including a credential written to a log or output; missing log - sanitization of credentials; credential storage or refresh in connection data that is wrong; a credential + secret stored in plain text, including a credential written to output; missing log + sanitization of credentials (masking, a minor fix; see Fix quality rules and How to record); credential storage or refresh in connection data that is wrong; a credential placement or host the provider API does not accept; user- or data-controlled URLs and hostnames that untrusted scenario data could use to steer a credential elsewhere; a privacy defect that exposes user content against the user's choice; and missing webhook verification, only when the provider documents a verification @@ -202,7 +305,7 @@ exposure that no change inside the app can remove leads to rejection. Never reje items, however many. How to record: a defect of class (a) to (d) uses the requirement-violation basis, Error severity and `blocks`; -an open question that could hide a scam uses the unverified basis, Warning severity and `needs_evidence`, and rejects the review when it stays unsettled; a fixed security, credential-handling or privacy defect is a security finding with the fix applied; an unproven privacy or security question that is not a scam is advisory; a +an open question that could hide a scam uses the unverified basis, Warning severity and `needs_evidence`, and rejects the review when it stays unsettled; a fixed security, credential-handling or privacy defect is a security finding with the fix applied; credential masking (a missing `log.sanitize` path) is a minor fix, recorded with Warning instead of Error severity, still `blocks` and fixed, and listed after the functional fixes, while a credential written to output or sent to another host is not masking and keeps Error severity; an unproven privacy or security question that is not a scam is advisory; a convention or quality point uses the recommendation or observation basis, Warning or Suggestion severity and `advisory`. State the single outcome (approve, approve with adjustments or reject) and, for adjustments, list each fix next to its finding; for a rejection, name the reason (scam, trash or an unremovable exposure). Name a service-specific field only where the review service diff --git a/skills/make-custom-apps/references/review-sweeps.md b/skills/make-custom-apps/references/review-sweeps.md index 5de28c4..ded6fb4 100644 --- a/skills/make-custom-apps/references/review-sweeps.md +++ b/skills/make-custom-apps/references/review-sweeps.md @@ -10,7 +10,7 @@ For each applicable check, record: source/rule, strength (documented requirement | Sweep | Inspect | Decide yourself (a name or locator is not enough) | Guide | | --- | --- | --- | --- | -| Temporal fields | Every emitted date/time field: output expression or helper, interface declaration, sample | Meaning, provider zone and unit; whether the conversion is real; exceptions (date-only, time-only, unknown zone, non-timestamp numbers). Cursor mapping is separate from output typing; `parseDate` absence alone proves nothing. JSON ISO text is text and a `date` interface is not proof of conversion; raw ISO pass-through is a conversion recommendation with a documented source ambiguity, not an automatic blocker; an already-Date traced value needs no second parse. | [dates-helpers](../examples/current-knowledge/guides/dates-helpers.md) | +| Temporal fields | Every emitted date/time field: output expression or helper, interface declaration, sample | Meaning, provider zone and unit; whether the conversion is real; exceptions (date-only, time-only, unknown zone, non-timestamp numbers). Cursor mapping is separate from output typing; check the conversion, not the `parseDate` token. JSON ISO text is text and a `date` interface is not proof of conversion; raw ISO pass-through is parsed with the provider's format (Required in marketplace review), an undocumented zone is uncertain rather than dismissed, and an already-Date traced value, such as one the app's own IML function parses, needs no second parse. | [dates-helpers](../examples/current-knowledge/guides/dates-helpers.md) | | Request headers | Universal subtype, all input branches, input-to-header sink, Base auth, collection vs expression form | REST: is any equivalent header input present and reaching the request. GraphQL: no Headers input is not by itself a REST-convention finding, but still check that provider-required headers can be sent. Credential retention is a separate trace; collision ordering is a bounded model, not proven precedence. | [headers-merge](../examples/current-knowledge/guides/headers-merge.md) | | Selectors | Selector location, effective mode, mappability, RPC links and input counts, parent stores | Operation role and provider hierarchy. Get/Update/Delete mappable identifiers require edit mode; Search/List and Create are recommendations; many RPC inputs differ from many results. Do not invent lookup routes. | [selectors-mode](../examples/current-knowledge/guides/selectors-mode.md) | | Routes | Exact method and path; provider documentation and its completeness | Whether the evidence is authoritative and exhaustive for that operation. Absence from partial documentation is an evidence gap, never a proven broken route; a deprecated route is not thereby removed. | [compatibility-evidence](../examples/current-knowledge/guides/compatibility-evidence.md) | @@ -25,6 +25,90 @@ For each applicable check, record: source/rule, strength (documented requirement | Output, interface, samples | Output projection or spread, interface entries, sample values, and the actual interface and empty-value handling in the output | Names, types and samples agree; omit, clear and set behave as promised; falsy values survive. Dates are one case of this, not the whole check. | [interfaces-required](../examples/current-knowledge/guides/interfaces-required.md), [outputs-empty-values-updates](../examples/current-knowledge/guides/outputs-empty-values-updates.md) | | Endpoints | Only if the request or review scope names SDK Endpoints | Endpoints are optional; absence is not a finding. Review them only when explicitly in scope. | [optional-endpoints](../examples/current-knowledge/guides/optional-endpoints.md) | +### Sweep: lookup results that build the next request + +Inspect every request array in which an earlier request stores a value from its response in +`temp` (often the first item of a filtered list, such as `body.items[1].id`) and a later +request puts that value into its `url`, path, query, body or headers. + +Decide whether the lookup can succeed without a usable value: a list or search that answers +2xx with an empty list, or a documented optional field that is absent. A missing path resolves +to empty without any error, and an empty value inside URL text becomes an empty string, so the +next request silently runs against a different or malformed route. A write can land on a +parent route or the collection root, a read on a malformed path, and the user sees a confusing +provider error or none at all. A 4xx for no match already stops the module through error +handling, before `valid` runs; the silent case is the 2xx one. + +- A route whose documented response is a list or search result can answer a no-match with an + empty 2xx list; that documentation is enough evidence. An unguarded chain on it is a + functional defect (class (a) in [Approval gating](review-and-qa.md#2a-approval-gating)). Fix + it on the lookup request with `response.valid` and a message that names the missing input. + Where an absent value is a legitimate outcome, give the later request a `condition` instead + (object form with `default` when the module must still return something). Apply the same fix + to every module that repeats the lookup. +- When the provider documentation cannot settle the no-match behaviour (for example a + single-object route whose not-found answer is undocumented), record the check as `uncertain` + with that missing fact rather than adding an unexplained guard. +- The lookup itself is legitimate ([requests, files and multi-step](../examples/current-knowledge/guides/requests-files-multistep.md)); + its extra request per run is a design point, not a finding. + +```json +[ + { + "url": "/lists", + "qs": { "name": "{{parameters.listName}}" }, + "response": { + "valid": { + "condition": "{{length(body.items) > 0}}", + "message": "No list named '{{parameters.listName}}' was found." + }, + "temp": { "listId": "{{body.items[1].id}}" } + } + }, + { "url": "/lists/{{temp.listId}}/entries", "method": "POST", "body": "{{parameters.entry}}" } +] +``` + +Guide: [errors and rate limits](../examples/current-knowledge/guides/errors-and-rate-limits.md) +(failures inside successful responses; errors in multi-step communication). + +### Sweep: comments and commented-out code + +Component files are parsed as JSON with comments, and approved apps were seen shipping comments +routinely: template explanations, notes, and commented-out alternative requests, option blocks +or whole `pagination` blocks. A comment does nothing at runtime, so it is neither a defect nor +evidence. Read every comment anyway, as the author's own statement about the component, and +test it against the active code: + +- A comment that admits a gap names a check to run: "add pagination" on an options RPC, a + commented-out `pagination` block, a TODO about unhandled error fields, or a note that a + provider field cannot drive the stop condition. Apply the matching sweep or checklist item + to the active code (pagination where the provider pages, the RPC record budget, documented + error shapes) and report what that check finds, not the comment. +- A comment that claims behaviour is not proof. A pagination body that writes + `"filters": { /* unchanged */ }` needs the conditional rules and evidence requirements in + [pagination and trigger state](../examples/current-knowledge/guides/pagination-and-trigger-state.md#identify-the-providers-protocol-first). + Check the request method and type, both body shapes, and `mergeWithParent` before deciding + which fields carry forward. Do not report lost filters or repeat the complete body solely + because of the comment; apply the guide's rule for that case and verify any claimed loss + against the continuation request. +- The comment or the dead code itself is cosmetic: never blocking, and not a reason to delete + or rewrite it when no finding requires the change. A change that only removes comments would + turn a plain approve into an adjustment for nothing. When building, resolve the gap a TODO + names instead of shipping the note, and keep one active definition instead of a + commented-out alternative, so the next reviewer does not have to guess which one is meant. + +## Mandatory per-component checklist + +For every component, answer each item below as `finding`, `passed`, `not_applicable` or `uncertain` with the missing fact (never skip silently): + +- Output dates are parsed to the Make date type where the provider value is a real timestamp. +- Documented error shapes (4xx bodies, including 422 validation errors) are handled in Base or the module, consistent with the provider. +- Authentication is inherited from Base or the connection and not duplicated in modules. +- Pagination exists where the provider pages results: for list and search modules and also for pickers and RPCs; RPC paging stays within the RPC record budget above. +- Output and interface agree: no stale or missing fields. +- File inputs and outputs keep their file semantics (name, data, MIME type). + ## Auth-alias counterexample review A difference in spelling (`data.x` vs `parameters.x`, or `common`) is not a static defect by itself. Before reporting, trace the specific OAuth phase (authorize, token, info, refresh, invalidate; Base; module) and the store the value actually lives in. In connection communication `data`, `parameters` and `connection` reach the same stored data; `common` is a separate store with its own role. This holds in the initial authorization-code token exchange as well as refresh. An empty `common: {}` does not mean credentials are missing when they are supplied as connection inputs, and `common` is not an alias: a read of `common.x` with the value only in inputs, or the reverse, is a real source-selection gap. In an ordinary module, `data` is persistent module state, `parameters` are inputs and `connection` is the attached store; do not transfer token-phase aliases there. Do not claim namespace equivalence outside the traced context, or that a live flow works from static reading. A real defect is a response-only variable in a request, a literal credential, or a module reading credentials from a store the actual flow never populates. See the worked case in [auth-context](../examples/current-knowledge/guides/auth-context.md#worked-case-initial-authorization-code-token-exchange-with-empty-common). diff --git a/skills/make-custom-apps/references/sdk-endpoints.md b/skills/make-custom-apps/references/sdk-endpoints.md index b7edca2..adf5fb9 100644 --- a/skills/make-custom-apps/references/sdk-endpoints.md +++ b/skills/make-custom-apps/references/sdk-endpoints.md @@ -33,6 +33,37 @@ are likewise preserved. - **Annotations:** select `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint` and `arbitraryCallHint` from actual effects, not HTTP verbs. A POST query can be read-only; idempotence needs provider evidence. Hints are neither permission grants nor retry guarantees.[1] +- **Run-time-chosen effects:** when an input such as a prompt, query statement or script lets the provider + choose the operation at run time (for example an agent that picks its own tools), set the hints from the + widest effect that input allows, not from typical or example input. If it can create or update records, + set `readOnlyHint: false`; if those updates can overwrite data, set `destructiveHint: true`; if repeating + the same input can create again, set `idempotentHint: false`. Keep `readOnlyHint: true` only when the + provider itself restricts the channel to reads, and cite that restriction in context. In context, also say + that an autonomous or no-confirmation flag removes only the pause, not the effect. +- **Write results:** when a create, update or duplicate does not return the stored resource (only + identifiers, an empty success such as 204, or a partial object while the provider finishes the work + asynchronously), say so in context and name the exact Endpoint that reads it back; pass any async or + status flag the provider returns through unchanged. If the new identifier arrives only in a response + header such as `Location`, map that header into the output instead of returning an empty object, and add + no success field the provider did not send. Otherwise callers treat a partial write result as final. +- **Value facts:** record in context what the output types cannot show: timestamps that are not ISO or not + in the expected unit (with the conversion factor); numbers or amounts sent as strings; JSON-encoded text + or union results whose shape depends on another field (name that field); raw codes and the Endpoint that + resolves them; relative URLs and the host they resolve against; fields omitted rather than `null`; and + expiries or caps such as cursor or pre-signed URL lifetimes and maximum retrievable rows. Also state what + an unknown or inaccessible ID returns: an error, an empty object or an empty list. +- **Cheaper alternatives:** when the provider meters by query cost, payload size or a per-operation rate + limit, state this Endpoint's own extra limit in context and name, by exact Endpoint or input name, the + cheaper way the app offers for common needs: an aggregate or query Endpoint instead of one read per + record, or field selection instead of the full object. Callers and agents choose Endpoints from these + descriptions. +- **Caller-chosen fields:** when a query Endpoint lets the caller choose fields, aggregates or columns, the + record shape depends on the input. Declare the records with the generic shape the Interface page documents + for unknown structures (an array without `spec`, or a collection with `"spec": []`) or with only the fields + every record carries, and keep continuation metadata in separate typed outputs. In help or context, say that + only requested fields return, what returns when none are requested, how keys are formed (aliases, case), and + which identifier to request for each follow-up Endpoint, named exactly (for example "request `id` for + `getRecord` and `updateRecord`"). ## 3. Implement and verify request semantics @@ -57,15 +88,19 @@ requirement. Any helper must exist before use and preserve the operation's valid containers, false/zero, dates and intentional clearing. For an in-scope generic fallback, keep `arbitraryCall` separate from regular operations and set -`arbitraryCallHint: true`.[1] Derive its base/version prefix and nonstandard request behavior from the -existing API-call module or verified Base; constrain destinations to the authorized provider. Test method, -headers, query, Content-Type, structured bodies and already-serialized text. Reproduce a serializer defect -on the selected runtime before adding a workaround; do not assume an old defect still applies. +`arbitraryCallHint: true`.[1] Derive its base prefix and version handling, and its nonstandard request +behavior, from the existing API-call module or verified Base; constrain destinations to the authorized +provider. Test method, headers, query, Content-Type, structured bodies and already-serialized text. +Reproduce a serializer defect on the selected runtime before adding a workaround; do not assume an old +defect still applies. A JSON execution envelope is not raw-file transport. Prefer documented URL/base64 inputs where suitable; verify provider-facing binary/multipart support end-to-end rather than claiming a universal ban or inventing an equivalent operation. +Record the tested empty-value results in context: which empty inputs are dropped, which are sent as given, +which value or flag clears a field, and what this Endpoint cannot clear; mark untested cases as unverified. + ## 4. Save in stages and read back 1. Read current app/version/origin, Endpoint metadata and sections; preserve unrelated/concurrent edits. diff --git a/skills/make-custom-apps/references/webhooks-and-polling.md b/skills/make-custom-apps/references/webhooks-and-polling.md index 158da1a..970e362 100644 --- a/skills/make-custom-apps/references/webhooks-and-polling.md +++ b/skills/make-custom-apps/references/webhooks-and-polling.md @@ -20,6 +20,24 @@ several events. Do not invent attach/detach endpoints from a provider's event na Sources: [Webhook types](https://developers.make.com/custom-apps-documentation/app-components/webhooks.md), [Dedicated webhooks](https://developers.make.com/custom-apps-documentation/app-components/webhooks/dedicated.md). +### Callback URL sent with each job request + +Some providers have no subscription endpoint. Instead, each job-creating request +accepts a callback URL, and the provider posts the result there when the job ends. +Model this as manual registration: + +- Use a non-attached dedicated webhook (no attach or detach) and an instant trigger. + Make generates the address when the user creates the webhook in that trigger. The job + module does not receive that address, so it offers an optional URL field for it. The + field's help names the watch module whose address belongs there, and the trigger's + banner explains the same pairing. +- If the job module also offers a mode that waits for the result with + [bounded asynchronous polling](requests-and-responses.md#bounded-asynchronous-polling-with-repeat), + do not send the callback URL in that mode, or the result reaches both the module and + the watch module. Say in help that the waiting mode does not start the watch module. + +Source: [Manual registration](https://developers.make.com/custom-apps-documentation/app-components/webhooks/dedicated/not-attached.md). + ## Implement attach and detach together 1. Link the instant trigger to the intended webhook definition and connection. @@ -134,6 +152,35 @@ with an appropriate IML conversion; do not manufacture timestamps to mask missin Source: [Polling trigger contract](https://developers.make.com/custom-apps-documentation/app-components/modules/trigger.md). +### Polls that change provider state + +Some sources change state when they are read. A queue receive can hide each item +for a lease period, and a list option can mark fetched items as read or processed. +Classify such a trigger request as a write, as +[requests and responses](requests-and-responses.md#independent-writes-in-one-module) +does for any request with side effects, not as a plain read. + +- The epoch inherits the trigger's request, so each opening of **Choose where to start** + also leases or marks the items it lists. Where the provider documents one, override + the epoch request with a non-claiming variant, such as a zero lease or a peek. +- Make restores its saved trigger progress after a failed run, but not the provider-side + change. A leased item stays hidden until its lease expires, an item marked as read no + longer matches a filter on unread items, and an item that returns with a date older + than the saved progress is skipped by a date trigger. No module reports an error. +- Make chooses the items to emit only after the trigger's requests have run: it drops + items already covered by the saved progress, sorts, and applies the limit. A marking + flag on the list request therefore also marks items that Make drops or holds back for + a later run, and a follow-up request inside the trigger cannot know which items were + emitted. Prefer a separate action module that marks or acknowledges items after the + scenario has processed them. Keep any built-in marking option off by default and say + in help what it changes. +- When the lease length is a parameter, give it a safe default within the provider's + documented range, and say in help that retrieved items stay hidden for that time and + come back unless they are deleted or acknowledged. + +Sources: [Epoch inheritance](https://developers.make.com/custom-apps-documentation/component-blocks/epoch.md), +[Polling trigger contract](https://developers.make.com/custom-apps-documentation/app-components/modules/trigger.md). + ## Current-knowledge guides - Date-only, time-only and unknown-timezone values, trigger order and helper tracing: @@ -157,3 +204,68 @@ different starting options; test the options appropriate to the selected trigger A linked trigger and successful upload do not prove registration or receipt. Source: [Epoch inheritance and output](https://developers.make.com/custom-apps-documentation/component-blocks/epoch.md). + +### Epoch overrides and the dates users pick from + +The epoch request is the trigger's request plus the epoch's overrides, so review the +two files together rather than the epoch alone. + +- Put an override where the trigger actually sends that value. When the trigger posts + its query in `body`, an epoch override in `qs` does not replace it. The epoch still + sends the inherited body, now with an extra query parameter. The provider, not the + epoch, then decides which query runs, so an intended override (a smaller field set or + page size) can be silently ignored. +- Map `output.date` from the same field and conversion as `trigger.date`. The start + point a user picks comes from the inherited `response.trigger` values, so a date from + another field (such as a creation date on an update trigger) shows the user a different + timeline from the one the cursor follows. +- Check that `label` and `date` read fields the iterated items really contain. Blank + labels or missing dates in the panel mean the epoch maps names the response lacks. + +~~~json +{ + "response": { + "limit": 300, + "output": { + "label": "{{item.title}}", + "date": "{{parseDate(item.updatedAt, 'X')}}" + } + } +} +~~~ + +The fragment assumes a trigger whose `trigger.date` is +`{{parseDate(item.updatedAt, 'X')}}` and whose items carry `title`. Copy the +trigger's expression rather than retyping it. + +Sources: [Epoch inheritance and output](https://developers.make.com/custom-apps-documentation/component-blocks/epoch.md), +[Trigger best practices](https://developers.make.com/custom-apps-documentation/best-practices/trigger-modules.md). + +### A trigger that still matches the starter template + +A new trigger module can start from an editor template. The template requests a +placeholder `/users` list, iterates `body.users`, uses `item.id` and `item.created` for +the trigger, has an epoch that labels items with `item.name` and dates them with +`item.created`, a user-shaped interface (`id`, `email`, `name`, `created`), empty +samples and tutorial comments. It is easy to leave all of this in place under a +resource-specific label. It is also easy to adapt the request but keep the template's +epoch field names. Either way the module uploads and validates, then returns the +wrong resource or blank **Choose where to start** entries. + +When reviewing a trigger, confirm that these all describe one resource and one field +set: the module label and description, `url`, `response.iterate`, `trigger.id` and +`trigger.date`, the epoch `output`, the interface and samples, and `scope`. Leftover +template comments are a prompt for this check, not a defect on their own. The response +fragment under polling progress uses the same placeholder names, so a trigger that +matches it still needs provider evidence. An executable module in the intended review scope +with this mismatch, including a newly created hidden module, has the +functional label mismatch described in [review sweeps](review-sweeps.md), a class (a) +defect under [Approval gating](review-and-qa.md#2a-approval-gating): fix it when the +provider documentation determines the resource and fields; otherwise report an +unverified advisory finding that names the missing fact. Hidden status alone does not prove +retirement; require evidence of retirement and exclusion from the intended review scope as +[Leftover editor-template modules](review-and-qa.md#leftover-editor-template-modules) +describes before leaving a template implementation unchanged. One leftover template module +does not make the app trash. + +Source: [Epoch inheritance and output](https://developers.make.com/custom-apps-documentation/component-blocks/epoch.md).