@particle-academy/fancy-connector-core 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1388,6 +1388,104 @@ declare function idempotencyKeyFor(ctx: unknown, nodeId: string, options?: Idemp
1388
1388
  */
1389
1389
  declare const NO_IDEMPOTENCY_KEY_WARNING: string;
1390
1390
 
1391
+ /**
1392
+ * A subscription that EXPIRES, and when the host must act on it.
1393
+ *
1394
+ * `DeliveryMechanism` has said since 0.1.0 that a `subscription` trigger is a
1395
+ * webhook somebody has to renew, forever, and that if nobody does the workflow
1396
+ * stops firing with no error anywhere. This is the value for that duty — ONE
1397
+ * shape every expiring trigger declares, so a host runs one renewal scheduler
1398
+ * rather than learning a loop per connector, each with its own boundary bugs.
1399
+ *
1400
+ * Three facts and two verbs:
1401
+ *
1402
+ * - `expiresAt` — the provider's expiry, as an RFC 3339 instant. Google Calendar
1403
+ * hands back `expiration` as epoch MILLISECONDS in a string and Microsoft
1404
+ * Graph hands back `expirationDateTime` as ISO 8601; the CONNECTOR converts on
1405
+ * the way in, and this module refuses anything that is not an instant rather
1406
+ * than guessing units.
1407
+ * - `renewBeforeSeconds` — the connector's margin. Positive, because zero would
1408
+ * make `due` unreachable (the moment it applied, `expired` would win) — a
1409
+ * lease nobody ever renews, declared in a way nothing would report.
1410
+ * - `renewOperation` — the operation the host calls when the lease is due. For
1411
+ * Graph that is a renew; for a Google Calendar channel, which cannot be
1412
+ * renewed, it is the create again (the connector stops the old channel
1413
+ * itself). The lease says WHEN; the connector says WHAT.
1414
+ *
1415
+ * - `leaseState` — where the lease IS: `active`, `due` (inclusive at renewAt),
1416
+ * `expired` (inclusive at expiresAt, and it wins over `due`: a lease that has
1417
+ * just expired cannot be renewed).
1418
+ * - `leaseAction` — what the host DOES: `none`, `renew`, or `resync`. A missed
1419
+ * lease is never a quiet re-create: notifications during the gap are gone, so
1420
+ * the host must re-list (sync token or full) AND re-subscribe.
1421
+ *
1422
+ * The boundaries are DECIDED, not measured, and they are pinned in
1423
+ * fancy-conformance's `shared/subscription-lease` suite, which drives the PHP
1424
+ * twin too (`tests/subscription-lease.test.ts` and its Pest mirror).
1425
+ */
1426
+
1427
+ type SubscriptionLease = {
1428
+ /** The provider's expiry, an RFC 3339 instant. */
1429
+ expiresAt: string;
1430
+ /** How early the host renews, in seconds. Positive. */
1431
+ renewBeforeSeconds: number;
1432
+ /** The operation the host calls when the lease is due. */
1433
+ renewOperation: string;
1434
+ };
1435
+ type LeaseState = "active" | "due" | "expired";
1436
+ type LeaseAction = "none" | "renew" | "resync";
1437
+ /**
1438
+ * How a provider spells its expiry. Two, because two providers: Google
1439
+ * Calendar's channel `expiration` is epoch MILLISECONDS (as a JSON string, and
1440
+ * a number is accepted too); Microsoft Graph's `expirationDateTime` is ISO
1441
+ * 8601 with a seven-digit fraction. A unit no shipped provider spells is not
1442
+ * here — a vocabulary with no provider is a claim that outruns the code.
1443
+ *
1444
+ * Data as well as a type: a host validates a definition at the JSON boundary,
1445
+ * where `tsc` cannot see.
1446
+ */
1447
+ declare const EXPIRES_AT_UNITS: readonly ["rfc3339", "epoch-ms"];
1448
+ type ExpiresAtUnit = (typeof EXPIRES_AT_UNITS)[number];
1449
+ /**
1450
+ * What a subscription trigger DECLARES about its lease, so a host can build
1451
+ * the value from the provider's create (or renew) response without knowing
1452
+ * the provider.
1453
+ */
1454
+ type LeaseDeclaration = {
1455
+ /** Dotted path to the expiry in the create/renew response, e.g. `expiration` or `channel.expiration`. */
1456
+ expiresAtFrom: string;
1457
+ expiresAtUnit: ExpiresAtUnit;
1458
+ /** How early the host renews, in seconds. Positive. */
1459
+ renewBeforeSeconds: number;
1460
+ /** The operation the host calls when the lease is due. */
1461
+ renewOperation: string;
1462
+ };
1463
+ /**
1464
+ * Build the lease from the provider's create (or renew) response, by
1465
+ * declaration. The declared unit is never guessed around: digits under
1466
+ * `rfc3339`, or an instant under `epoch-ms`, are refused — a lease built from
1467
+ * a misread expiry is one that expires unannounced.
1468
+ *
1469
+ * The expiry is stored as an RFC 3339 instant in UTC at millisecond
1470
+ * precision; the lease's own refusals (margin, operation) still apply.
1471
+ */
1472
+ declare function leaseFromResponse(declaration: LeaseDeclaration, response: unknown, at?: ConnectorErrorContext): SubscriptionLease;
1473
+ /**
1474
+ * Validate a declaration and return the lease — a plain value a host stores
1475
+ * beside the trigger and hands back to `leaseState` / `leaseAction` later.
1476
+ */
1477
+ declare function subscriptionLease(input: {
1478
+ expiresAt: string;
1479
+ renewBeforeSeconds: number;
1480
+ renewOperation: string;
1481
+ }, at?: ConnectorErrorContext): SubscriptionLease;
1482
+ /** The instant the lease becomes due: `expiresAt - renewBeforeSeconds`. */
1483
+ declare function leaseRenewAt(lease: SubscriptionLease): string;
1484
+ /** Where the lease is at `now`. Both boundaries are inclusive; `expired` wins. */
1485
+ declare function leaseState(lease: SubscriptionLease, now: string | Date): LeaseState;
1486
+ /** What the host does about the lease at `now`. */
1487
+ declare function leaseAction(lease: SubscriptionLease, now: string | Date): LeaseAction;
1488
+
1391
1489
  /**
1392
1490
  * Measuring and slicing text the way providers actually measure and slice it.
1393
1491
  *
@@ -2058,6 +2156,58 @@ declare function providerProblems(provider: ProviderAdapter): string[];
2058
2156
  /** True when a provider's declared sandbox can actually be selected at run time. */
2059
2157
  declare function providerSandboxIsSelectable(provider: ProviderAdapter): boolean;
2060
2158
 
2159
+ /**
2160
+ * Raw MIME in, headers / parts / attachments out — the payload TRANSFORM an
2161
+ * inbound-email trigger declares.
2162
+ *
2163
+ * Written from scratch (the owner: no third-party code), as ONE implementation
2164
+ * in two runtimes — `php/src/Mime.php` is the twin — and held to the authored
2165
+ * corpus under `fixtures/mime/`, which both must reproduce byte for byte.
2166
+ * `fixtures/mime/README.md` lists every decision a case pins; the ones that
2167
+ * are easy to get differently in two languages are restated here:
2168
+ *
2169
+ * - Header lines are read as Latin-1 (one byte, one char), unfolded with a
2170
+ * single space, names lowercased, values RFC 2047-decoded (B and Q; adjacent
2171
+ * encoded-words join without the whitespace between them).
2172
+ * - The line break before a boundary delimiter belongs to the DELIMITER.
2173
+ * - `size` is the transfer-decoded byte length, before any charset conversion.
2174
+ * - A text part comes back as UTF-8 with the message's own line endings. A
2175
+ * charset this module does not decode (anything but utf-8, us-ascii,
2176
+ * iso-8859-1, iso-8859-15, windows-1252) leaves the part with no text.
2177
+ * - Every non-text leaf is an attachment, as is a text leaf declared
2178
+ * `attachment`; attachments carry their bytes as base64. `filename*` (RFC
2179
+ * 2231) wins over `filename`, which wins over Content-Type's `name`.
2180
+ * - `messageId` is the header verbatim; `contentId` has its angle brackets
2181
+ * stripped, because `cid:` references omit them.
2182
+ */
2183
+ type MimeHeader = {
2184
+ name: string;
2185
+ value: string;
2186
+ };
2187
+ type MimePart = {
2188
+ index: number;
2189
+ contentType: string;
2190
+ charset: string | null;
2191
+ disposition: "inline" | "attachment" | null;
2192
+ filename: string | null;
2193
+ contentId: string | null;
2194
+ size: number;
2195
+ headers: MimeHeader[];
2196
+ };
2197
+ type MimeAttachment = MimePart & {
2198
+ content: string;
2199
+ };
2200
+ type MimeMessage = {
2201
+ headers: MimeHeader[];
2202
+ subject: string | null;
2203
+ messageId: string | null;
2204
+ text: string | null;
2205
+ html: string | null;
2206
+ parts: MimePart[];
2207
+ attachments: MimeAttachment[];
2208
+ };
2209
+ declare function parseMime(raw: Uint8Array | string): MimeMessage;
2210
+
2061
2211
  /**
2062
2212
  * Dry-verify — proving the transport with a credential that cannot work.
2063
2213
  *
@@ -2222,6 +2372,58 @@ declare function hmac(secret: string, payload: string, algorithm: HmacScheme["al
2222
2372
  * attacker nothing they could not compute.
2223
2373
  */
2224
2374
  declare function constantTimeEquals(a: string, b: string): boolean;
2375
+ /**
2376
+ * A delivery verified by a token the provider ECHOES rather than a signature
2377
+ * it computes.
2378
+ *
2379
+ * Google Calendar sends the channel's `token` back in `X-Goog-Channel-Token`
2380
+ * on every notification — with an EMPTY body, so there is nothing to sign.
2381
+ * Microsoft Graph sends `clientState` inside every item of the notification's
2382
+ * `value` array. Same refusal-by-default as HMAC, same result shape, and a
2383
+ * constant-time comparison: a token is a secret, and `===` leaks which prefix
2384
+ * was right.
2385
+ *
2386
+ * A body `path` is dotted; a segment ending in `[]` means EVERY element of that
2387
+ * array, all of which must match — one wrong item refuses the whole delivery.
2388
+ */
2389
+ type SharedTokenScheme = {
2390
+ kind: "shared-token";
2391
+ in: "header";
2392
+ name: string;
2393
+ } | {
2394
+ kind: "shared-token";
2395
+ in: "body";
2396
+ path: string;
2397
+ };
2398
+ declare function isSharedTokenScheme(scheme: HmacScheme | SharedTokenScheme): scheme is SharedTokenScheme;
2399
+ declare function verifySharedToken(options: {
2400
+ raw: string;
2401
+ headers: Record<string, string | string[] | undefined>;
2402
+ secret: string | undefined;
2403
+ scheme: SharedTokenScheme;
2404
+ }): WebhookVerification;
2405
+ /**
2406
+ * A challenge the provider makes BEFORE it will deliver anything, answered by
2407
+ * echoing a query parameter as plain text. Microsoft Graph POSTs
2408
+ * `?validationToken=…` to the notification URL when a subscription is created
2409
+ * and refuses to create it unless the token comes back, decoded, as
2410
+ * `text/plain` within ten seconds.
2411
+ *
2412
+ * Declared as data on the trigger so a host can answer it in its own routing
2413
+ * layer; `handshakeResponse` is the pure half — what to send, or `undefined`
2414
+ * when the request is not a challenge at all.
2415
+ */
2416
+ type ChallengeHandshake = {
2417
+ kind: "echo-query";
2418
+ /** The query parameter carrying the challenge. */
2419
+ param: string;
2420
+ contentType?: "text/plain";
2421
+ };
2422
+ declare function handshakeResponse(handshake: ChallengeHandshake | undefined, query: Record<string, string | string[] | undefined>): {
2423
+ status: 200;
2424
+ contentType: string;
2425
+ body: string;
2426
+ } | undefined;
2225
2427
  /**
2226
2428
  * Pull one header case-insensitively.
2227
2429
  *
@@ -2272,6 +2474,13 @@ type TriggerDescriptor = {
2272
2474
  setup: string;
2273
2475
  /** For `subscription`: how long the provider keeps it alive, in seconds. */
2274
2476
  subscriptionTtl?: number;
2477
+ /**
2478
+ * For `subscription`: where the provider's expiry sits in the create/renew
2479
+ * response and how it is spelled, so a host builds the `SubscriptionLease`
2480
+ * with `leaseFromResponse` and runs ONE renewal scheduler for every
2481
+ * expiring trigger.
2482
+ */
2483
+ lease?: LeaseDeclaration;
2275
2484
  /** For `webhook` / `subscription`: how a delivery is authenticated. */
2276
2485
  verification?: WebhookVerificationSpec;
2277
2486
  /** For `poll`: the provider's smallest sane interval, in seconds. */
@@ -2279,7 +2488,8 @@ type TriggerDescriptor = {
2279
2488
  /** A faked sample event, so the node is runnable before any of the above. */
2280
2489
  faker: ConnectorFaker;
2281
2490
  };
2282
- type WebhookVerificationSpec = {
2491
+ /** The provider SIGNS each delivery. */
2492
+ type HmacVerificationSpec = {
2283
2493
  /** Header carrying the signature. */
2284
2494
  signatureHeader: string;
2285
2495
  /** Header carrying the timestamp, when the scheme signs one. */
@@ -2293,7 +2503,20 @@ type WebhookVerificationSpec = {
2293
2503
  signature?: string;
2294
2504
  timestamp?: string;
2295
2505
  };
2506
+ /** A challenge the provider makes before it will deliver anything. */
2507
+ handshake?: ChallengeHandshake;
2508
+ };
2509
+ /**
2510
+ * The provider ECHOES a token the subscriber chose. Google Calendar's channel
2511
+ * token, Graph's `clientState`. See `SharedTokenScheme`.
2512
+ */
2513
+ type SharedTokenVerificationSpec = {
2514
+ scheme: SharedTokenScheme;
2515
+ /** A challenge the provider makes before it will deliver anything. */
2516
+ handshake?: ChallengeHandshake;
2296
2517
  };
2518
+ type WebhookVerificationSpec = HmacVerificationSpec | SharedTokenVerificationSpec;
2519
+ declare function isSharedTokenSpec(spec: WebhookVerificationSpec): spec is SharedTokenVerificationSpec;
2297
2520
  type InboundDelivery = {
2298
2521
  /** The body EXACTLY as received. Not re-serialised. See `webhook.ts`. */
2299
2522
  raw: string;
@@ -2323,4 +2546,4 @@ declare function verifyDelivery(trigger: TriggerDescriptor, delivery: InboundDel
2323
2546
  */
2324
2547
  declare function triggerEvent(trigger: TriggerDescriptor, connection: ResolvedConnection, injected: unknown, config: Record<string, unknown>): unknown;
2325
2548
 
2326
- export { AMBIGUOUS_REFUSAL, type ApiContract, type Attempt, type ByteRange, CANONICAL_METRICS, CONNECTOR_API_VERSION, CONNECTOR_MODES, CREDENTIAL_SCOPES, type CallOptions, type CallResult, type Capabilities, type Catalogue, type ChainLinks, type ChainOutcome, type ChainRef, type Citation, type Classified, type ConnectionCredentials, type ConnectionHost, type ConnectionSpec, type Connector, ConnectorAmbiguous, ConnectorApiMismatch, ConnectorAuthError, ConnectorConfigError, ConnectorError, type ConnectorErrorContext, type ConnectorFaker, ConnectorIdempotencyExpiredError, type ConnectorMode, ConnectorModeError, ConnectorRateLimited, type ConnectorRequest, ConnectorRequestError, type ConnectorResult, ConnectorTransient, ConnectorUnreachable, type ContractOperation, type CredentialField, type CredentialScope, DEFAULT_IDEMPOTENCY_WINDOW_SECONDS, DEFAULT_RETRY, type DeliveryDeclaration, type DeliveryMechanism, type DeliveryOutcome, type DriftFinding, type DriftReport, FAKE_EPOCH, type FailureKind, type FakeRequest, type FakeValues, type HmacScheme, type HostEnvironment, type IdempotencyOptions, type InboundDelivery, MAX_IDEMPOTENCY_KEY_LENGTH, type MetricDescriptor, type MetricSample, type ModeInputs, NO_IDEMPOTENCY_KEY_WARNING, PROBLEM_SEVERITIES, type PreparedRequest, type ProbeOutcome, type ProbeReport, type ProbeResult, type ProbeSpec, type Problem, type ProviderAdapter, RENDERER_VERSION, REVIEW_STALE_DAYS, type RecordedShape, type RenderRules, type RenderedPayload, type RequestedMode, type ResolveOptions, type ResolvedConnection, type RetryPolicy, type RunIdentity, SANDBOX_KINDS, SUPPORTED_CONNECTOR_API, type SandboxKind, type Segment, type ServiceDescriptor, type SetupStep, type ShapeMismatch, type SpecSource, type TextUnit, type Transport, type TransportResponse, type TriggerDescriptor, type VerifyResult, type WebhookVerification, type WebhookVerificationSpec, assertConnectorApi, byteRangeOf, callConnector, capabilityProblems, checkAgainstOpenApi, checkAgainstRecordedShape, classifyError, classifyHttp, classifyStatus, classifyThrown, compareShape, connectionsFor, constantTimeEquals, deliver, fakeRequest, fakeValues, getConnectionHost, graphemes, header, hmac, httpFailure, idempotencyKeyFor, isEmptyPayload, isRemote, isUnconditionallyRetryable, linkRanges, measure, payloadHash, postChain, probe, providerProblems, providerSandboxIsSelectable, registerConnectionHost, registerTransport, render, reported, resetRateState, resolveConnection, resolveConnectorMode, respectRate, runIdentityFrom, runKeyFrom, runProbes, sandboxIsSelectable, sandboxRefusal, satisfiesMinimum, seedFrom, shapeOf, shouldRetry, sliceByteRange, splitToFit, triggerEvent, unchecked, utf8Length, verifyDelivery, verifyHmac, withResolvedLimit };
2549
+ export { AMBIGUOUS_REFUSAL, type ApiContract, type Attempt, type ByteRange, CANONICAL_METRICS, CONNECTOR_API_VERSION, CONNECTOR_MODES, CREDENTIAL_SCOPES, type CallOptions, type CallResult, type Capabilities, type Catalogue, type ChainLinks, type ChainOutcome, type ChainRef, type ChallengeHandshake, type Citation, type Classified, type ConnectionCredentials, type ConnectionHost, type ConnectionSpec, type Connector, ConnectorAmbiguous, ConnectorApiMismatch, ConnectorAuthError, ConnectorConfigError, ConnectorError, type ConnectorErrorContext, type ConnectorFaker, ConnectorIdempotencyExpiredError, type ConnectorMode, ConnectorModeError, ConnectorRateLimited, type ConnectorRequest, ConnectorRequestError, type ConnectorResult, ConnectorTransient, ConnectorUnreachable, type ContractOperation, type CredentialField, type CredentialScope, DEFAULT_IDEMPOTENCY_WINDOW_SECONDS, DEFAULT_RETRY, type DeliveryDeclaration, type DeliveryMechanism, type DeliveryOutcome, type DriftFinding, type DriftReport, EXPIRES_AT_UNITS, type ExpiresAtUnit, FAKE_EPOCH, type FailureKind, type FakeRequest, type FakeValues, type HmacScheme, type HmacVerificationSpec, type HostEnvironment, type IdempotencyOptions, type InboundDelivery, type LeaseAction, type LeaseDeclaration, type LeaseState, MAX_IDEMPOTENCY_KEY_LENGTH, type MetricDescriptor, type MetricSample, type MimeAttachment, type MimeHeader, type MimeMessage, type MimePart, type ModeInputs, NO_IDEMPOTENCY_KEY_WARNING, PROBLEM_SEVERITIES, type PreparedRequest, type ProbeOutcome, type ProbeReport, type ProbeResult, type ProbeSpec, type Problem, type ProviderAdapter, RENDERER_VERSION, REVIEW_STALE_DAYS, type RecordedShape, type RenderRules, type RenderedPayload, type RequestedMode, type ResolveOptions, type ResolvedConnection, type RetryPolicy, type RunIdentity, SANDBOX_KINDS, SUPPORTED_CONNECTOR_API, type SandboxKind, type Segment, type ServiceDescriptor, type SetupStep, type ShapeMismatch, type SharedTokenScheme, type SharedTokenVerificationSpec, type SpecSource, type SubscriptionLease, type TextUnit, type Transport, type TransportResponse, type TriggerDescriptor, type VerifyResult, type WebhookVerification, type WebhookVerificationSpec, assertConnectorApi, byteRangeOf, callConnector, capabilityProblems, checkAgainstOpenApi, checkAgainstRecordedShape, classifyError, classifyHttp, classifyStatus, classifyThrown, compareShape, connectionsFor, constantTimeEquals, deliver, fakeRequest, fakeValues, getConnectionHost, graphemes, handshakeResponse, header, hmac, httpFailure, idempotencyKeyFor, isEmptyPayload, isRemote, isSharedTokenScheme, isSharedTokenSpec, isUnconditionallyRetryable, leaseAction, leaseFromResponse, leaseRenewAt, leaseState, linkRanges, measure, parseMime, payloadHash, postChain, probe, providerProblems, providerSandboxIsSelectable, registerConnectionHost, registerTransport, render, reported, resetRateState, resolveConnection, resolveConnectorMode, respectRate, runIdentityFrom, runKeyFrom, runProbes, sandboxIsSelectable, sandboxRefusal, satisfiesMinimum, seedFrom, shapeOf, shouldRetry, sliceByteRange, splitToFit, subscriptionLease, triggerEvent, unchecked, utf8Length, verifyDelivery, verifyHmac, verifySharedToken, withResolvedLimit };
package/dist/index.d.ts CHANGED
@@ -1388,6 +1388,104 @@ declare function idempotencyKeyFor(ctx: unknown, nodeId: string, options?: Idemp
1388
1388
  */
1389
1389
  declare const NO_IDEMPOTENCY_KEY_WARNING: string;
1390
1390
 
1391
+ /**
1392
+ * A subscription that EXPIRES, and when the host must act on it.
1393
+ *
1394
+ * `DeliveryMechanism` has said since 0.1.0 that a `subscription` trigger is a
1395
+ * webhook somebody has to renew, forever, and that if nobody does the workflow
1396
+ * stops firing with no error anywhere. This is the value for that duty — ONE
1397
+ * shape every expiring trigger declares, so a host runs one renewal scheduler
1398
+ * rather than learning a loop per connector, each with its own boundary bugs.
1399
+ *
1400
+ * Three facts and two verbs:
1401
+ *
1402
+ * - `expiresAt` — the provider's expiry, as an RFC 3339 instant. Google Calendar
1403
+ * hands back `expiration` as epoch MILLISECONDS in a string and Microsoft
1404
+ * Graph hands back `expirationDateTime` as ISO 8601; the CONNECTOR converts on
1405
+ * the way in, and this module refuses anything that is not an instant rather
1406
+ * than guessing units.
1407
+ * - `renewBeforeSeconds` — the connector's margin. Positive, because zero would
1408
+ * make `due` unreachable (the moment it applied, `expired` would win) — a
1409
+ * lease nobody ever renews, declared in a way nothing would report.
1410
+ * - `renewOperation` — the operation the host calls when the lease is due. For
1411
+ * Graph that is a renew; for a Google Calendar channel, which cannot be
1412
+ * renewed, it is the create again (the connector stops the old channel
1413
+ * itself). The lease says WHEN; the connector says WHAT.
1414
+ *
1415
+ * - `leaseState` — where the lease IS: `active`, `due` (inclusive at renewAt),
1416
+ * `expired` (inclusive at expiresAt, and it wins over `due`: a lease that has
1417
+ * just expired cannot be renewed).
1418
+ * - `leaseAction` — what the host DOES: `none`, `renew`, or `resync`. A missed
1419
+ * lease is never a quiet re-create: notifications during the gap are gone, so
1420
+ * the host must re-list (sync token or full) AND re-subscribe.
1421
+ *
1422
+ * The boundaries are DECIDED, not measured, and they are pinned in
1423
+ * fancy-conformance's `shared/subscription-lease` suite, which drives the PHP
1424
+ * twin too (`tests/subscription-lease.test.ts` and its Pest mirror).
1425
+ */
1426
+
1427
+ type SubscriptionLease = {
1428
+ /** The provider's expiry, an RFC 3339 instant. */
1429
+ expiresAt: string;
1430
+ /** How early the host renews, in seconds. Positive. */
1431
+ renewBeforeSeconds: number;
1432
+ /** The operation the host calls when the lease is due. */
1433
+ renewOperation: string;
1434
+ };
1435
+ type LeaseState = "active" | "due" | "expired";
1436
+ type LeaseAction = "none" | "renew" | "resync";
1437
+ /**
1438
+ * How a provider spells its expiry. Two, because two providers: Google
1439
+ * Calendar's channel `expiration` is epoch MILLISECONDS (as a JSON string, and
1440
+ * a number is accepted too); Microsoft Graph's `expirationDateTime` is ISO
1441
+ * 8601 with a seven-digit fraction. A unit no shipped provider spells is not
1442
+ * here — a vocabulary with no provider is a claim that outruns the code.
1443
+ *
1444
+ * Data as well as a type: a host validates a definition at the JSON boundary,
1445
+ * where `tsc` cannot see.
1446
+ */
1447
+ declare const EXPIRES_AT_UNITS: readonly ["rfc3339", "epoch-ms"];
1448
+ type ExpiresAtUnit = (typeof EXPIRES_AT_UNITS)[number];
1449
+ /**
1450
+ * What a subscription trigger DECLARES about its lease, so a host can build
1451
+ * the value from the provider's create (or renew) response without knowing
1452
+ * the provider.
1453
+ */
1454
+ type LeaseDeclaration = {
1455
+ /** Dotted path to the expiry in the create/renew response, e.g. `expiration` or `channel.expiration`. */
1456
+ expiresAtFrom: string;
1457
+ expiresAtUnit: ExpiresAtUnit;
1458
+ /** How early the host renews, in seconds. Positive. */
1459
+ renewBeforeSeconds: number;
1460
+ /** The operation the host calls when the lease is due. */
1461
+ renewOperation: string;
1462
+ };
1463
+ /**
1464
+ * Build the lease from the provider's create (or renew) response, by
1465
+ * declaration. The declared unit is never guessed around: digits under
1466
+ * `rfc3339`, or an instant under `epoch-ms`, are refused — a lease built from
1467
+ * a misread expiry is one that expires unannounced.
1468
+ *
1469
+ * The expiry is stored as an RFC 3339 instant in UTC at millisecond
1470
+ * precision; the lease's own refusals (margin, operation) still apply.
1471
+ */
1472
+ declare function leaseFromResponse(declaration: LeaseDeclaration, response: unknown, at?: ConnectorErrorContext): SubscriptionLease;
1473
+ /**
1474
+ * Validate a declaration and return the lease — a plain value a host stores
1475
+ * beside the trigger and hands back to `leaseState` / `leaseAction` later.
1476
+ */
1477
+ declare function subscriptionLease(input: {
1478
+ expiresAt: string;
1479
+ renewBeforeSeconds: number;
1480
+ renewOperation: string;
1481
+ }, at?: ConnectorErrorContext): SubscriptionLease;
1482
+ /** The instant the lease becomes due: `expiresAt - renewBeforeSeconds`. */
1483
+ declare function leaseRenewAt(lease: SubscriptionLease): string;
1484
+ /** Where the lease is at `now`. Both boundaries are inclusive; `expired` wins. */
1485
+ declare function leaseState(lease: SubscriptionLease, now: string | Date): LeaseState;
1486
+ /** What the host does about the lease at `now`. */
1487
+ declare function leaseAction(lease: SubscriptionLease, now: string | Date): LeaseAction;
1488
+
1391
1489
  /**
1392
1490
  * Measuring and slicing text the way providers actually measure and slice it.
1393
1491
  *
@@ -2058,6 +2156,58 @@ declare function providerProblems(provider: ProviderAdapter): string[];
2058
2156
  /** True when a provider's declared sandbox can actually be selected at run time. */
2059
2157
  declare function providerSandboxIsSelectable(provider: ProviderAdapter): boolean;
2060
2158
 
2159
+ /**
2160
+ * Raw MIME in, headers / parts / attachments out — the payload TRANSFORM an
2161
+ * inbound-email trigger declares.
2162
+ *
2163
+ * Written from scratch (the owner: no third-party code), as ONE implementation
2164
+ * in two runtimes — `php/src/Mime.php` is the twin — and held to the authored
2165
+ * corpus under `fixtures/mime/`, which both must reproduce byte for byte.
2166
+ * `fixtures/mime/README.md` lists every decision a case pins; the ones that
2167
+ * are easy to get differently in two languages are restated here:
2168
+ *
2169
+ * - Header lines are read as Latin-1 (one byte, one char), unfolded with a
2170
+ * single space, names lowercased, values RFC 2047-decoded (B and Q; adjacent
2171
+ * encoded-words join without the whitespace between them).
2172
+ * - The line break before a boundary delimiter belongs to the DELIMITER.
2173
+ * - `size` is the transfer-decoded byte length, before any charset conversion.
2174
+ * - A text part comes back as UTF-8 with the message's own line endings. A
2175
+ * charset this module does not decode (anything but utf-8, us-ascii,
2176
+ * iso-8859-1, iso-8859-15, windows-1252) leaves the part with no text.
2177
+ * - Every non-text leaf is an attachment, as is a text leaf declared
2178
+ * `attachment`; attachments carry their bytes as base64. `filename*` (RFC
2179
+ * 2231) wins over `filename`, which wins over Content-Type's `name`.
2180
+ * - `messageId` is the header verbatim; `contentId` has its angle brackets
2181
+ * stripped, because `cid:` references omit them.
2182
+ */
2183
+ type MimeHeader = {
2184
+ name: string;
2185
+ value: string;
2186
+ };
2187
+ type MimePart = {
2188
+ index: number;
2189
+ contentType: string;
2190
+ charset: string | null;
2191
+ disposition: "inline" | "attachment" | null;
2192
+ filename: string | null;
2193
+ contentId: string | null;
2194
+ size: number;
2195
+ headers: MimeHeader[];
2196
+ };
2197
+ type MimeAttachment = MimePart & {
2198
+ content: string;
2199
+ };
2200
+ type MimeMessage = {
2201
+ headers: MimeHeader[];
2202
+ subject: string | null;
2203
+ messageId: string | null;
2204
+ text: string | null;
2205
+ html: string | null;
2206
+ parts: MimePart[];
2207
+ attachments: MimeAttachment[];
2208
+ };
2209
+ declare function parseMime(raw: Uint8Array | string): MimeMessage;
2210
+
2061
2211
  /**
2062
2212
  * Dry-verify — proving the transport with a credential that cannot work.
2063
2213
  *
@@ -2222,6 +2372,58 @@ declare function hmac(secret: string, payload: string, algorithm: HmacScheme["al
2222
2372
  * attacker nothing they could not compute.
2223
2373
  */
2224
2374
  declare function constantTimeEquals(a: string, b: string): boolean;
2375
+ /**
2376
+ * A delivery verified by a token the provider ECHOES rather than a signature
2377
+ * it computes.
2378
+ *
2379
+ * Google Calendar sends the channel's `token` back in `X-Goog-Channel-Token`
2380
+ * on every notification — with an EMPTY body, so there is nothing to sign.
2381
+ * Microsoft Graph sends `clientState` inside every item of the notification's
2382
+ * `value` array. Same refusal-by-default as HMAC, same result shape, and a
2383
+ * constant-time comparison: a token is a secret, and `===` leaks which prefix
2384
+ * was right.
2385
+ *
2386
+ * A body `path` is dotted; a segment ending in `[]` means EVERY element of that
2387
+ * array, all of which must match — one wrong item refuses the whole delivery.
2388
+ */
2389
+ type SharedTokenScheme = {
2390
+ kind: "shared-token";
2391
+ in: "header";
2392
+ name: string;
2393
+ } | {
2394
+ kind: "shared-token";
2395
+ in: "body";
2396
+ path: string;
2397
+ };
2398
+ declare function isSharedTokenScheme(scheme: HmacScheme | SharedTokenScheme): scheme is SharedTokenScheme;
2399
+ declare function verifySharedToken(options: {
2400
+ raw: string;
2401
+ headers: Record<string, string | string[] | undefined>;
2402
+ secret: string | undefined;
2403
+ scheme: SharedTokenScheme;
2404
+ }): WebhookVerification;
2405
+ /**
2406
+ * A challenge the provider makes BEFORE it will deliver anything, answered by
2407
+ * echoing a query parameter as plain text. Microsoft Graph POSTs
2408
+ * `?validationToken=…` to the notification URL when a subscription is created
2409
+ * and refuses to create it unless the token comes back, decoded, as
2410
+ * `text/plain` within ten seconds.
2411
+ *
2412
+ * Declared as data on the trigger so a host can answer it in its own routing
2413
+ * layer; `handshakeResponse` is the pure half — what to send, or `undefined`
2414
+ * when the request is not a challenge at all.
2415
+ */
2416
+ type ChallengeHandshake = {
2417
+ kind: "echo-query";
2418
+ /** The query parameter carrying the challenge. */
2419
+ param: string;
2420
+ contentType?: "text/plain";
2421
+ };
2422
+ declare function handshakeResponse(handshake: ChallengeHandshake | undefined, query: Record<string, string | string[] | undefined>): {
2423
+ status: 200;
2424
+ contentType: string;
2425
+ body: string;
2426
+ } | undefined;
2225
2427
  /**
2226
2428
  * Pull one header case-insensitively.
2227
2429
  *
@@ -2272,6 +2474,13 @@ type TriggerDescriptor = {
2272
2474
  setup: string;
2273
2475
  /** For `subscription`: how long the provider keeps it alive, in seconds. */
2274
2476
  subscriptionTtl?: number;
2477
+ /**
2478
+ * For `subscription`: where the provider's expiry sits in the create/renew
2479
+ * response and how it is spelled, so a host builds the `SubscriptionLease`
2480
+ * with `leaseFromResponse` and runs ONE renewal scheduler for every
2481
+ * expiring trigger.
2482
+ */
2483
+ lease?: LeaseDeclaration;
2275
2484
  /** For `webhook` / `subscription`: how a delivery is authenticated. */
2276
2485
  verification?: WebhookVerificationSpec;
2277
2486
  /** For `poll`: the provider's smallest sane interval, in seconds. */
@@ -2279,7 +2488,8 @@ type TriggerDescriptor = {
2279
2488
  /** A faked sample event, so the node is runnable before any of the above. */
2280
2489
  faker: ConnectorFaker;
2281
2490
  };
2282
- type WebhookVerificationSpec = {
2491
+ /** The provider SIGNS each delivery. */
2492
+ type HmacVerificationSpec = {
2283
2493
  /** Header carrying the signature. */
2284
2494
  signatureHeader: string;
2285
2495
  /** Header carrying the timestamp, when the scheme signs one. */
@@ -2293,7 +2503,20 @@ type WebhookVerificationSpec = {
2293
2503
  signature?: string;
2294
2504
  timestamp?: string;
2295
2505
  };
2506
+ /** A challenge the provider makes before it will deliver anything. */
2507
+ handshake?: ChallengeHandshake;
2508
+ };
2509
+ /**
2510
+ * The provider ECHOES a token the subscriber chose. Google Calendar's channel
2511
+ * token, Graph's `clientState`. See `SharedTokenScheme`.
2512
+ */
2513
+ type SharedTokenVerificationSpec = {
2514
+ scheme: SharedTokenScheme;
2515
+ /** A challenge the provider makes before it will deliver anything. */
2516
+ handshake?: ChallengeHandshake;
2296
2517
  };
2518
+ type WebhookVerificationSpec = HmacVerificationSpec | SharedTokenVerificationSpec;
2519
+ declare function isSharedTokenSpec(spec: WebhookVerificationSpec): spec is SharedTokenVerificationSpec;
2297
2520
  type InboundDelivery = {
2298
2521
  /** The body EXACTLY as received. Not re-serialised. See `webhook.ts`. */
2299
2522
  raw: string;
@@ -2323,4 +2546,4 @@ declare function verifyDelivery(trigger: TriggerDescriptor, delivery: InboundDel
2323
2546
  */
2324
2547
  declare function triggerEvent(trigger: TriggerDescriptor, connection: ResolvedConnection, injected: unknown, config: Record<string, unknown>): unknown;
2325
2548
 
2326
- export { AMBIGUOUS_REFUSAL, type ApiContract, type Attempt, type ByteRange, CANONICAL_METRICS, CONNECTOR_API_VERSION, CONNECTOR_MODES, CREDENTIAL_SCOPES, type CallOptions, type CallResult, type Capabilities, type Catalogue, type ChainLinks, type ChainOutcome, type ChainRef, type Citation, type Classified, type ConnectionCredentials, type ConnectionHost, type ConnectionSpec, type Connector, ConnectorAmbiguous, ConnectorApiMismatch, ConnectorAuthError, ConnectorConfigError, ConnectorError, type ConnectorErrorContext, type ConnectorFaker, ConnectorIdempotencyExpiredError, type ConnectorMode, ConnectorModeError, ConnectorRateLimited, type ConnectorRequest, ConnectorRequestError, type ConnectorResult, ConnectorTransient, ConnectorUnreachable, type ContractOperation, type CredentialField, type CredentialScope, DEFAULT_IDEMPOTENCY_WINDOW_SECONDS, DEFAULT_RETRY, type DeliveryDeclaration, type DeliveryMechanism, type DeliveryOutcome, type DriftFinding, type DriftReport, FAKE_EPOCH, type FailureKind, type FakeRequest, type FakeValues, type HmacScheme, type HostEnvironment, type IdempotencyOptions, type InboundDelivery, MAX_IDEMPOTENCY_KEY_LENGTH, type MetricDescriptor, type MetricSample, type ModeInputs, NO_IDEMPOTENCY_KEY_WARNING, PROBLEM_SEVERITIES, type PreparedRequest, type ProbeOutcome, type ProbeReport, type ProbeResult, type ProbeSpec, type Problem, type ProviderAdapter, RENDERER_VERSION, REVIEW_STALE_DAYS, type RecordedShape, type RenderRules, type RenderedPayload, type RequestedMode, type ResolveOptions, type ResolvedConnection, type RetryPolicy, type RunIdentity, SANDBOX_KINDS, SUPPORTED_CONNECTOR_API, type SandboxKind, type Segment, type ServiceDescriptor, type SetupStep, type ShapeMismatch, type SpecSource, type TextUnit, type Transport, type TransportResponse, type TriggerDescriptor, type VerifyResult, type WebhookVerification, type WebhookVerificationSpec, assertConnectorApi, byteRangeOf, callConnector, capabilityProblems, checkAgainstOpenApi, checkAgainstRecordedShape, classifyError, classifyHttp, classifyStatus, classifyThrown, compareShape, connectionsFor, constantTimeEquals, deliver, fakeRequest, fakeValues, getConnectionHost, graphemes, header, hmac, httpFailure, idempotencyKeyFor, isEmptyPayload, isRemote, isUnconditionallyRetryable, linkRanges, measure, payloadHash, postChain, probe, providerProblems, providerSandboxIsSelectable, registerConnectionHost, registerTransport, render, reported, resetRateState, resolveConnection, resolveConnectorMode, respectRate, runIdentityFrom, runKeyFrom, runProbes, sandboxIsSelectable, sandboxRefusal, satisfiesMinimum, seedFrom, shapeOf, shouldRetry, sliceByteRange, splitToFit, triggerEvent, unchecked, utf8Length, verifyDelivery, verifyHmac, withResolvedLimit };
2549
+ export { AMBIGUOUS_REFUSAL, type ApiContract, type Attempt, type ByteRange, CANONICAL_METRICS, CONNECTOR_API_VERSION, CONNECTOR_MODES, CREDENTIAL_SCOPES, type CallOptions, type CallResult, type Capabilities, type Catalogue, type ChainLinks, type ChainOutcome, type ChainRef, type ChallengeHandshake, type Citation, type Classified, type ConnectionCredentials, type ConnectionHost, type ConnectionSpec, type Connector, ConnectorAmbiguous, ConnectorApiMismatch, ConnectorAuthError, ConnectorConfigError, ConnectorError, type ConnectorErrorContext, type ConnectorFaker, ConnectorIdempotencyExpiredError, type ConnectorMode, ConnectorModeError, ConnectorRateLimited, type ConnectorRequest, ConnectorRequestError, type ConnectorResult, ConnectorTransient, ConnectorUnreachable, type ContractOperation, type CredentialField, type CredentialScope, DEFAULT_IDEMPOTENCY_WINDOW_SECONDS, DEFAULT_RETRY, type DeliveryDeclaration, type DeliveryMechanism, type DeliveryOutcome, type DriftFinding, type DriftReport, EXPIRES_AT_UNITS, type ExpiresAtUnit, FAKE_EPOCH, type FailureKind, type FakeRequest, type FakeValues, type HmacScheme, type HmacVerificationSpec, type HostEnvironment, type IdempotencyOptions, type InboundDelivery, type LeaseAction, type LeaseDeclaration, type LeaseState, MAX_IDEMPOTENCY_KEY_LENGTH, type MetricDescriptor, type MetricSample, type MimeAttachment, type MimeHeader, type MimeMessage, type MimePart, type ModeInputs, NO_IDEMPOTENCY_KEY_WARNING, PROBLEM_SEVERITIES, type PreparedRequest, type ProbeOutcome, type ProbeReport, type ProbeResult, type ProbeSpec, type Problem, type ProviderAdapter, RENDERER_VERSION, REVIEW_STALE_DAYS, type RecordedShape, type RenderRules, type RenderedPayload, type RequestedMode, type ResolveOptions, type ResolvedConnection, type RetryPolicy, type RunIdentity, SANDBOX_KINDS, SUPPORTED_CONNECTOR_API, type SandboxKind, type Segment, type ServiceDescriptor, type SetupStep, type ShapeMismatch, type SharedTokenScheme, type SharedTokenVerificationSpec, type SpecSource, type SubscriptionLease, type TextUnit, type Transport, type TransportResponse, type TriggerDescriptor, type VerifyResult, type WebhookVerification, type WebhookVerificationSpec, assertConnectorApi, byteRangeOf, callConnector, capabilityProblems, checkAgainstOpenApi, checkAgainstRecordedShape, classifyError, classifyHttp, classifyStatus, classifyThrown, compareShape, connectionsFor, constantTimeEquals, deliver, fakeRequest, fakeValues, getConnectionHost, graphemes, handshakeResponse, header, hmac, httpFailure, idempotencyKeyFor, isEmptyPayload, isRemote, isSharedTokenScheme, isSharedTokenSpec, isUnconditionallyRetryable, leaseAction, leaseFromResponse, leaseRenewAt, leaseState, linkRanges, measure, parseMime, payloadHash, postChain, probe, providerProblems, providerSandboxIsSelectable, registerConnectionHost, registerTransport, render, reported, resetRateState, resolveConnection, resolveConnectorMode, respectRate, runIdentityFrom, runKeyFrom, runProbes, sandboxIsSelectable, sandboxRefusal, satisfiesMinimum, seedFrom, shapeOf, shouldRetry, sliceByteRange, splitToFit, subscriptionLease, triggerEvent, unchecked, utf8Length, verifyDelivery, verifyHmac, verifySharedToken, withResolvedLimit };