@superlayer/webhooks 1.0.67
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/LICENSE.md +202 -0
- package/NOTICE +4 -0
- package/README.md +387 -0
- package/dist/commonjs/__types__/typeUtils.d.ts +12 -0
- package/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
- package/dist/commonjs/__types__/typeUtils.js +5 -0
- package/dist/commonjs/__types__/typeUtils.js.map +1 -0
- package/dist/commonjs/__types__/typesTests.d.ts +2 -0
- package/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
- package/dist/commonjs/__types__/typesTests.js +79 -0
- package/dist/commonjs/__types__/typesTests.js.map +1 -0
- package/dist/commonjs/index.d.ts +588 -0
- package/dist/commonjs/index.d.ts.map +1 -0
- package/dist/commonjs/index.js +756 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/esm/__types__/typeUtils.d.ts +12 -0
- package/dist/esm/__types__/typeUtils.d.ts.map +1 -0
- package/dist/esm/__types__/typeUtils.js +4 -0
- package/dist/esm/__types__/typeUtils.js.map +1 -0
- package/dist/esm/__types__/typesTests.d.ts +2 -0
- package/dist/esm/__types__/typesTests.d.ts.map +1 -0
- package/dist/esm/__types__/typesTests.js +77 -0
- package/dist/esm/__types__/typesTests.js.map +1 -0
- package/dist/esm/index.d.ts +588 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +751 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/package.json +70 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
InterfaceDB SDK
|
|
2
|
+
Derived from Instant (https://github.com/instantdb/instant), revision 7607eda60547e0068f05aeb2c43ac92c6356f65d.
|
|
3
|
+
Original source copyrights and licence notices are retained.
|
|
4
|
+
Modified by InterfaceDB: npm package names, service defaults, tooling and documentation.
|
package/README.md
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# @superlayer/webhooks
|
|
2
|
+
|
|
3
|
+
Webhook handlers for Superlayer.
|
|
4
|
+
|
|
5
|
+
[Documentation](https://interfacedb.com/docs) · [Source](https://github.com/InterfaceLDN/Superlayer)
|
|
6
|
+
|
|
7
|
+
Maintained by Superlayer, based on the Instant source. See LICENSE.md and NOTICE for attribution.
|
|
8
|
+
|
|
9
|
+
Welcome to [Superlayer’s](https://interfacedb.com) webhooks library.
|
|
10
|
+
|
|
11
|
+
This package gives you the building blocks for working with Instant webhooks: verifying incoming requests, dispatching records to typed handlers, and managing webhook subscriptions and their delivery history.
|
|
12
|
+
|
|
13
|
+
# Where to use this
|
|
14
|
+
|
|
15
|
+
The `Webhooks` class is re-exported from a few places. Use whichever fits your setup:
|
|
16
|
+
|
|
17
|
+
- **From `@superlayer/admin`** — most apps. `db.webhooks` is wired up for you. An admin token is only required if you also want to manage webhooks (`db.webhooks.manager.*`); the receiving side (`processRequest` / `validate`) works without one.
|
|
18
|
+
- **From `@superlayer/platform`** — building on top of Instant on behalf of other users. `api.webhooks(appId)` returns a `Webhooks` instance, and the platform SDK transparently refreshes the OAuth token for manager calls. Auth is only required if you'll use `manager.*`.
|
|
19
|
+
- **Standalone from `@superlayer/webhooks`** — useful if you don't want to pull in the rest of the admin SDK. Again, no admin token is needed unless you'll call `manager.*`.
|
|
20
|
+
|
|
21
|
+
## From the admin SDK
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { init } from '@superlayer/admin';
|
|
25
|
+
import schema from './instant.schema';
|
|
26
|
+
|
|
27
|
+
// adminToken is optional if you're only using the SDK for the receiving side
|
|
28
|
+
// of webhooks (processRequest / validate / etc.). Include it if you also want
|
|
29
|
+
// to use db.webhooks.manager.* — or any other admin-SDK feature that requires
|
|
30
|
+
// auth, like writes or impersonation.
|
|
31
|
+
const db = init({
|
|
32
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
33
|
+
schema,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// db.webhooks is a Webhooks<typeof schema> instance.
|
|
37
|
+
await db.webhooks.processRequest(handlers, req);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## From the platform SDK
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { PlatformApi } from '@superlayer/platform';
|
|
44
|
+
import schema from './instant.schema';
|
|
45
|
+
|
|
46
|
+
// Auth is optional if you're only using PlatformApi for the receiving side of
|
|
47
|
+
// webhooks. Include it if you also want to use webhooks.manager.* (or any
|
|
48
|
+
// other platform-SDK feature). When provided, the platform SDK refreshes the
|
|
49
|
+
// OAuth token transparently for manager calls.
|
|
50
|
+
const api = new PlatformApi({ auth: { token: accessToken } });
|
|
51
|
+
|
|
52
|
+
const webhooks = api.webhooks(appId, { schema });
|
|
53
|
+
|
|
54
|
+
await webhooks.processRequest(handlers, req);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Standalone
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { Webhooks } from '@superlayer/webhooks';
|
|
61
|
+
import schema from './instant.schema';
|
|
62
|
+
|
|
63
|
+
// For receiving only (validate / processRequest / processPayload), the
|
|
64
|
+
// adminToken is optional — you just need appId + schema for typed handlers.
|
|
65
|
+
const webhooks = new Webhooks<typeof schema>({
|
|
66
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
67
|
+
schema,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
// To also manage webhooks (manager.create, manager.list, …) pass adminToken.
|
|
71
|
+
const webhooksWithManager = new Webhooks<typeof schema>({
|
|
72
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
73
|
+
adminToken: process.env.INSTANT_APP_ADMIN_TOKEN!,
|
|
74
|
+
schema,
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`new Webhooks(config)` accepts:
|
|
79
|
+
|
|
80
|
+
- `appId` — required for `manager.*`; recommended for the receiving side so error messages and helpers are scoped.
|
|
81
|
+
- `adminToken` (or `token`) — required for `manager.*`. Not needed to verify signatures or dispatch handlers.
|
|
82
|
+
- `schema` — optional. Pass your schema to get fully typed `record.before` / `record.after` in handlers and typed `namespaces` on `manager.create` / `manager.update`.
|
|
83
|
+
- `apiURI` — defaults to `https://api.interfacedb.com`. Override for self-hosted or local development.
|
|
84
|
+
- `withAuth` — advanced hook used by the platform SDK to inject a fresh OAuth token per request; you generally won't pass this directly.
|
|
85
|
+
|
|
86
|
+
The rest of this README uses `db.webhooks` in examples. The same methods exist on a standalone `Webhooks` instance or on `api.webhooks(appId)`.
|
|
87
|
+
|
|
88
|
+
# Receiving webhooks
|
|
89
|
+
|
|
90
|
+
## `processRequest(handlers, req, opts?)`
|
|
91
|
+
|
|
92
|
+
The one-liner for handling an incoming webhook. It:
|
|
93
|
+
|
|
94
|
+
1. Verifies the `Instant-Signature` header against the raw body.
|
|
95
|
+
2. Fetches the records via the short-lived `payloadUrl` + JWT in the body.
|
|
96
|
+
3. Dispatches each record to the matching handler.
|
|
97
|
+
|
|
98
|
+
Pass it a Web [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) (Next.js App Router, Cloudflare Workers, Deno, Bun, Hono, etc.):
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
// app/api/instant-webhook/route.ts
|
|
102
|
+
import { init } from '@superlayer/admin';
|
|
103
|
+
import schema from '@/instant.schema';
|
|
104
|
+
|
|
105
|
+
const db = init({
|
|
106
|
+
appId: process.env.INSTANT_APP_ID!,
|
|
107
|
+
schema,
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const { typedHandlers, combineHandlers } = db.webhooks.helpers();
|
|
111
|
+
|
|
112
|
+
const handlers = combineHandlers(
|
|
113
|
+
typedHandlers('posts', 'create', async (record) => {
|
|
114
|
+
await sendNewPostEmail(record.after);
|
|
115
|
+
}),
|
|
116
|
+
typedHandlers('posts', 'update', (record) => {
|
|
117
|
+
console.log('post %s changed', record.id, record.before, record.after);
|
|
118
|
+
}),
|
|
119
|
+
typedHandlers('$default', (record) => {
|
|
120
|
+
console.log('unhandled record', record);
|
|
121
|
+
}),
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
export async function POST(req: Request) {
|
|
125
|
+
await db.webhooks.processRequest(handlers, req);
|
|
126
|
+
return new Response('ok');
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Options:
|
|
131
|
+
|
|
132
|
+
- `tolerance` — max signature age in seconds (default `300`). Protects against replays; raising this weakens that.
|
|
133
|
+
- `receivedAt` — override the "now" used when checking signature age. Mostly useful in tests.
|
|
134
|
+
|
|
135
|
+
Handler resolution is most-specific-wins: `namespace` + `action` → that namespace's `$default` → top-level `$default`. Records with no matching handler are skipped.
|
|
136
|
+
|
|
137
|
+
Handlers run concurrently. `processRequest` resolves once all of them settle. If any handler rejects, the call rejects — return a non-2xx response so Instant retries the event.
|
|
138
|
+
|
|
139
|
+
## `processNodeRequest(handlers, req, opts?)`
|
|
140
|
+
|
|
141
|
+
Adapter for frameworks that hand you a Node-style `IncomingMessage` instead of a Web `Request` — Next.js Pages Router, Express, Koa, NestJS, Fastify, etc. The raw bytes of the body are required to verify the signature, so **don't put a JSON body parser in front of this route** (`express.json()`, Next's default `bodyParser`, etc.).
|
|
142
|
+
|
|
143
|
+
The adapter picks up the raw body from, in order: `opts.body`, `req.rawBody`, `req.body` (if it's a `Buffer`/`Uint8Array`/string), then the unconsumed request stream.
|
|
144
|
+
|
|
145
|
+
Next.js Pages Router:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
// pages/api/instant-webhook.ts
|
|
149
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
150
|
+
|
|
151
|
+
export const config = { api: { bodyParser: false } };
|
|
152
|
+
|
|
153
|
+
export default async function handler(
|
|
154
|
+
req: NextApiRequest,
|
|
155
|
+
res: NextApiResponse,
|
|
156
|
+
) {
|
|
157
|
+
try {
|
|
158
|
+
await db.webhooks.processNodeRequest(handlers, req);
|
|
159
|
+
res.status(200).end();
|
|
160
|
+
} catch (e) {
|
|
161
|
+
res.status(400).json({ error: String(e) });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Express (use `express.raw` on the webhook route only):
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
app.post(
|
|
170
|
+
'/webhooks/instant',
|
|
171
|
+
express.raw({ type: 'application/json' }),
|
|
172
|
+
async (req, res) => {
|
|
173
|
+
try {
|
|
174
|
+
await db.webhooks.processNodeRequest(handlers, req);
|
|
175
|
+
res.status(200).end();
|
|
176
|
+
} catch (e) {
|
|
177
|
+
res.status(400).json({ error: String(e) });
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
);
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Koa with `raw-body`:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
router.post('/webhooks/instant', async (ctx) => {
|
|
187
|
+
await db.webhooks.processNodeRequest(handlers, ctx.req, {
|
|
188
|
+
body: rawBody(ctx.req), // adapter awaits the Promise
|
|
189
|
+
});
|
|
190
|
+
ctx.status = 200;
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
NestJS (Express adapter, with `NestFactory.create(AppModule, { rawBody: true })`):
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
@Controller('webhooks')
|
|
198
|
+
export class WebhooksController {
|
|
199
|
+
@Post('instant')
|
|
200
|
+
@HttpCode(200)
|
|
201
|
+
async handle(@Req() req: Request) {
|
|
202
|
+
await db.webhooks.processNodeRequest(handlers, req);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
If the adapter detects that an upstream parser turned the body into an object, it re-serializes it and tries anyway — but if the bytes don't match what Instant signed, you'll get a targeted error telling you to switch the route off the JSON parser.
|
|
208
|
+
|
|
209
|
+
## `processPayload(handlers, payload)`
|
|
210
|
+
|
|
211
|
+
Dispatches a payload you've already fetched. Useful when you'd rather do signature verification yourself (or when you're replaying an event from `manager.getPayload`).
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
const body = await db.webhooks.validate(signatureHeader, rawBody);
|
|
215
|
+
const payload = await db.webhooks.fetchPayloads(body);
|
|
216
|
+
await db.webhooks.processPayload(handlers, payload);
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Same resolution rules and concurrency model as `processRequest`: handlers run in parallel, and if any of them rejects the call rejects too — return a non-2xx response so Instant retries the event. If you'd rather have a per-handler failure not fail the whole batch, wrap that handler's body in `try`/`catch`.
|
|
220
|
+
|
|
221
|
+
## `validate(signatureHeader, body, opts?)`
|
|
222
|
+
|
|
223
|
+
Parses an `Instant-Signature` header, verifies it against the body, and returns the `{ payloadUrl, token }` you'd use to fetch the records. Throws if the signature doesn't validate, is older than `opts.tolerance` (default 300 seconds), or the body isn't the expected shape.
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
const { payloadUrl, token } = await db.webhooks.validate(
|
|
227
|
+
signatureHeader,
|
|
228
|
+
rawBody,
|
|
229
|
+
{ tolerance: 300 },
|
|
230
|
+
);
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
`body` can be a string or a function returning a `Promise<string>` — pass the function form to defer reading the request stream until after the header has been parsed.
|
|
234
|
+
|
|
235
|
+
## `validateRequest(req, opts?)`
|
|
236
|
+
|
|
237
|
+
Convenience wrapper around `validate`: pulls `instant-signature` and the body off a Web `Request` for you.
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
const { payloadUrl, token } = await db.webhooks.validateRequest(req);
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
## `fetchPayloads({ payloadUrl, token })`
|
|
244
|
+
|
|
245
|
+
Exchanges the `{ payloadUrl, token }` from a validated body for the full payload of records. Returns a `WebhookPayload<Schema>`.
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
const payload = await db.webhooks.fetchPayloads({ payloadUrl, token });
|
|
249
|
+
console.log(payload.idempotencyKey, payload.data.length);
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
## `helpers()` and `Webhooks.helpers<Schema>()`
|
|
253
|
+
|
|
254
|
+
Schema-bound helpers for building typed handler maps:
|
|
255
|
+
|
|
256
|
+
- `typedHandlers(namespace, action, handler)` — typed entry for one `namespace` + `action`. Pass `'$default'` for `action` to handle every action for that namespace.
|
|
257
|
+
- `typedHandlers('$default', handler)` — top-level catch-all.
|
|
258
|
+
- `combineHandlers(...entries)` — merges entries into a single `WebhookHandlers` object suitable for `processRequest` / `processPayload`.
|
|
259
|
+
|
|
260
|
+
Two ways to get them:
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
// Instance form — infers Schema from the instance, no type argument needed.
|
|
264
|
+
const { typedHandlers, combineHandlers } = db.webhooks.helpers();
|
|
265
|
+
|
|
266
|
+
// Static form — useful when you don't have a Webhooks instance handy.
|
|
267
|
+
const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Inside each handler, `record.before` and `record.after` are typed according to your schema and narrowed on `action` (`create` ⇒ `before: null`, `delete` ⇒ `after: null`).
|
|
271
|
+
|
|
272
|
+
# Managing webhooks
|
|
273
|
+
|
|
274
|
+
`db.webhooks.manager` exposes CRUD on webhooks and access to their delivery history. All `manager.*` methods require an `adminToken` (admin SDK) or platform OAuth token (platform SDK).
|
|
275
|
+
|
|
276
|
+
## `manager.list()`
|
|
277
|
+
|
|
278
|
+
Returns every webhook configured on the app, newest first. Includes both active and disabled webhooks.
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
const webhooks = await db.webhooks.manager.list();
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
## `manager.create({ url, namespaces, actions })`
|
|
285
|
+
|
|
286
|
+
Creates a webhook in the `active` state. It starts receiving matching events immediately.
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
const webhook = await db.webhooks.manager.create({
|
|
290
|
+
url: 'https://example.com/instant',
|
|
291
|
+
namespaces: ['posts', 'comments'],
|
|
292
|
+
actions: ['create', 'update'],
|
|
293
|
+
});
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
The server rejects the request if `url` isn't an HTTPS URL pointing at a public host, if `namespaces` doesn't reference any entity in the app's schema, if `actions` is empty, or if the app has hit its **100 active webhooks** limit.
|
|
297
|
+
|
|
298
|
+
## `manager.update(webhookId, params)`
|
|
299
|
+
|
|
300
|
+
Patches `url`, `namespaces`, and/or `actions`. Omitted fields keep their current value. Does not affect status — use `enable` / `disable` for that.
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
await db.webhooks.manager.update(webhook.id, {
|
|
304
|
+
actions: ['create', 'update'],
|
|
305
|
+
});
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
## `manager.delete(webhookId)`
|
|
309
|
+
|
|
310
|
+
Deletes a webhook. No further events will be queued for it. Returns the webhook as it looked just before deletion.
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
await db.webhooks.manager.delete(webhook.id);
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
## `manager.enable(webhookId)`
|
|
317
|
+
|
|
318
|
+
Re-enables a disabled webhook. Clears `disabledReason` and resumes delivery for new events. Events that occurred while the webhook was disabled are **not** retroactively delivered.
|
|
319
|
+
|
|
320
|
+
```ts
|
|
321
|
+
await db.webhooks.manager.enable(webhook.id);
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
## `manager.disable(webhookId, opts?)`
|
|
325
|
+
|
|
326
|
+
Stops queuing new events for a webhook. In-flight events already being processed will still complete. Optionally attach a human-readable `reason` that shows up in the dashboard.
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
await db.webhooks.manager.disable(webhook.id, {
|
|
330
|
+
reason: 'paused for migration',
|
|
331
|
+
});
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
Instant also disables webhooks automatically after repeated delivery failures.
|
|
335
|
+
|
|
336
|
+
## `manager.listEvents(webhookId, opts?)`
|
|
337
|
+
|
|
338
|
+
Returns a page of delivery events for a webhook, newest first. Events are retained for ~60 days.
|
|
339
|
+
|
|
340
|
+
```ts
|
|
341
|
+
let cursor: string | null = null;
|
|
342
|
+
do {
|
|
343
|
+
const { events, pageInfo } = await db.webhooks.manager.listEvents(
|
|
344
|
+
webhook.id,
|
|
345
|
+
{
|
|
346
|
+
after: cursor,
|
|
347
|
+
},
|
|
348
|
+
);
|
|
349
|
+
for (const event of events) {
|
|
350
|
+
console.log(event.isn, event.status, event.attempts);
|
|
351
|
+
}
|
|
352
|
+
cursor = pageInfo.hasNextPage ? pageInfo.endCursor : null;
|
|
353
|
+
} while (cursor);
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
Each event's `attempts` array records, per attempt: HTTP status, response body (first 256 bytes), duration, and an `errorType` tag (`timeout`, `dns`, `connect`, `tls`, `protocol`, `network`, `unknown`) when delivery failed.
|
|
357
|
+
|
|
358
|
+
## `manager.getEvent(webhookId, isn)`
|
|
359
|
+
|
|
360
|
+
Fetches a single event by its `isn` (Instant Sequence Number).
|
|
361
|
+
|
|
362
|
+
```ts
|
|
363
|
+
const event = await db.webhooks.manager.getEvent(webhook.id, isn);
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
## `manager.getPayload(webhookId, isn)`
|
|
367
|
+
|
|
368
|
+
Returns the full payload (records + `idempotencyKey`) for an event. Useful for replaying delivery locally with `processPayload`.
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
const payload = await db.webhooks.manager.getPayload(webhook.id, isn);
|
|
372
|
+
await db.webhooks.processPayload(handlers, payload);
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
## `manager.resendEvent(webhookId, isn)`
|
|
376
|
+
|
|
377
|
+
Re-queues an event for delivery, regardless of its current status. Use this to retry a `failed` event or force a redelivery of a `success` one.
|
|
378
|
+
|
|
379
|
+
```ts
|
|
380
|
+
await db.webhooks.manager.resendEvent(webhook.id, isn);
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
Rate-limited per event — calling it twice in quick succession returns a validation error asking you to wait about a minute.
|
|
384
|
+
|
|
385
|
+
# Questions?
|
|
386
|
+
|
|
387
|
+
If you have any questions, feel free to drop us a line on our [issue tracker](https://github.com/InterfaceLDN/Superlayer/issues)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type Expect<T extends true> = T;
|
|
2
|
+
export type ExpectTrue<T extends true> = T;
|
|
3
|
+
export type ExpectFalse<T extends false> = T;
|
|
4
|
+
export type IsTrue<T extends true> = T;
|
|
5
|
+
export type IsFalse<T extends false> = T;
|
|
6
|
+
export type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;
|
|
7
|
+
export type NotEqual<X, Y> = true extends Equal<X, Y> ? false : true;
|
|
8
|
+
export type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
9
|
+
export type NotAny<T> = true extends IsAny<T> ? false : true;
|
|
10
|
+
export type IsNever<T> = [T] extends [never] ? true : false;
|
|
11
|
+
export type NotNever<T> = true extends IsNever<T> ? false : true;
|
|
12
|
+
//# sourceMappingURL=typeUtils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typeUtils.d.ts","sourceRoot":"","sources":["../../../src/__types__/typeUtils.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;AACvC,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;AAC3C,MAAM,MAAM,WAAW,CAAC,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC;AAC7C,MAAM,MAAM,MAAM,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;AACvC,MAAM,MAAM,OAAO,CAAC,CAAC,SAAS,KAAK,IAAI,CAAC,CAAC;AAEzC,MAAM,MAAM,KAAK,CAAC,CAAC,EAAE,CAAC,IACpB,CAAC,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,GAC/D,IAAI,GACJ,KAAK,CAAC;AACZ,MAAM,MAAM,QAAQ,CAAC,CAAC,EAAE,CAAC,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC;AAGrE,MAAM,MAAM,KAAK,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC;AACtD,MAAM,MAAM,MAAM,CAAC,CAAC,IAAI,IAAI,SAAS,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC;AAE7D,MAAM,MAAM,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC;AAC5D,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI,IAAI,SAAS,OAAO,CAAC,CAAC,CAAC,GAAG,KAAK,GAAG,IAAI,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typeUtils.js","sourceRoot":"","sources":["../../../src/__types__/typeUtils.ts"],"names":[],"mappings":";AAAA,0BAA0B;AAC1B,gFAAgF","sourcesContent":["// Type testing utils from\n// https://github.com/type-challenges/type-challenges/blob/main/utils/index.d.ts\n\nexport type Expect<T extends true> = T;\nexport type ExpectTrue<T extends true> = T;\nexport type ExpectFalse<T extends false> = T;\nexport type IsTrue<T extends true> = T;\nexport type IsFalse<T extends false> = T;\n\nexport type Equal<X, Y> =\n (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2\n ? true\n : false;\nexport type NotEqual<X, Y> = true extends Equal<X, Y> ? false : true;\n\n// https://stackoverflow.com/questions/49927523/disallow-call-with-any/49928360#49928360\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\nexport type NotAny<T> = true extends IsAny<T> ? false : true;\n\nexport type IsNever<T> = [T] extends [never] ? true : false;\nexport type NotNever<T> = true extends IsNever<T> ? false : true;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typesTests.d.ts","sourceRoot":"","sources":["../../../src/__types__/typesTests.ts"],"names":[],"mappings":""}
|