@withone/sdk 0.0.4 → 0.2.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.js CHANGED
@@ -1,9 +1,350 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2;
2
2
 
3
3
  var _chunkKPQGG74Ujs = require('./chunk-KPQGG74U.js');
4
4
 
5
5
  // src/client.ts
6
6
  var _nativejs = require('../native.js');
7
+
8
+ // src/errors.ts
9
+ var OneError = class extends Error {
10
+ constructor(code, message, status, body, retryable) {
11
+ super(message);
12
+ this.code = code;
13
+ this.status = status;
14
+ this.body = body;
15
+ this.retryable = retryable;
16
+ this.name = "OneError";
17
+ }
18
+
19
+
20
+
21
+
22
+ };
23
+ function toOneError(error) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ try {
26
+ const envelope = JSON.parse(message);
27
+ return new OneError(envelope.code, envelope.message, envelope.status, envelope.body, envelope.retryable);
28
+ } catch (e) {
29
+ return new OneError("unknown", message, void 0, void 0, false);
30
+ }
31
+ }
32
+
33
+ // src/webhooks.ts
34
+
35
+ var WebhooksBase = (_class = class {
36
+ constructor(client, options) {;_class.prototype.__init.call(this);_class.prototype.__init2.call(this);
37
+ this.client = client;
38
+ this.options = options;
39
+ }
40
+
41
+
42
+ __init() {this.handlers = /* @__PURE__ */ new Map()}
43
+ __init2() {this.anyHandlers = []}
44
+ /** @internal Registers a typed handler; generated methods wrap this. */
45
+ register(event, connection, run) {
46
+ const existing = _nullishCoalesce(this.handlers.get(event), () => ( []));
47
+ existing.push({ connection, run });
48
+ this.handlers.set(event, existing);
49
+ return this;
50
+ }
51
+ /**
52
+ * Registers handlers scoped to one connection: they fire only for deliveries
53
+ * carrying that connection's key.
54
+ *
55
+ * The block keeps the scope lexical, so a reader never has to scan backwards
56
+ * to work out which connection a handler belongs to, and only the
57
+ * connection-carrying events are offered inside it.
58
+ */
59
+ connection(key, block) {
60
+ const scope = new (this.scopeConstructor())(key);
61
+ block(scope);
62
+ for (const [event, registered] of scope.drain()) {
63
+ const existing = _nullishCoalesce(this.handlers.get(event), () => ( []));
64
+ existing.push(...registered);
65
+ this.handlers.set(event, existing);
66
+ }
67
+ this.anyHandlers.push(...scope.drainAny());
68
+ return this;
69
+ }
70
+ /** @internal The generated subclass supplies its own scope type. */
71
+ scopeConstructor() {
72
+ return ConnectionWebhooksBase;
73
+ }
74
+ /**
75
+ * Registers a handler fired for every verified delivery, including event
76
+ * types this SDK build does not recognize. Runs after event-specific
77
+ * handlers.
78
+ */
79
+ onAny(handler) {
80
+ this.anyHandlers.push({ connection: null, run: handler });
81
+ return this;
82
+ }
83
+ /**
84
+ * The event types `listen` subscribes to.
85
+ *
86
+ * An unscoped catch-all subscribes to this build's whole catalog; the server
87
+ * matches exact event strings, so events added after this build are not
88
+ * covered. A catch-all scoped to a connection adds only the
89
+ * connection-carrying events, since the server cannot filter by connection
90
+ * and the rest would just be discarded on arrival.
91
+ */
92
+ events() {
93
+ if (this.anyHandlers.some((handler) => handler.connection === null)) return [...this.catalog()];
94
+ const events = new Set(this.handlers.keys());
95
+ if (this.anyHandlers.length > 0) {
96
+ for (const event of this.connectionCatalog()) events.add(event);
97
+ }
98
+ return [...events].sort();
99
+ }
100
+ /** @internal The generated subclass supplies the full event catalog. */
101
+ catalog() {
102
+ return [];
103
+ }
104
+ /** @internal The generated subclass supplies the connection-carrying subset. */
105
+ connectionCatalog() {
106
+ return [];
107
+ }
108
+ /**
109
+ * Verifies the signature and freshness of a delivery without dispatching.
110
+ * Use it when you want to route deliveries yourself.
111
+ *
112
+ * `rawBody` must be the exact bytes One sent. A JSON body parser that has
113
+ * already re-serialized the request will fail verification.
114
+ */
115
+ verify(rawBody, signature) {
116
+ try {
117
+ const verified = _nativejs.verifyWebhook.call(void 0, rawBody, signature, this.options.secret, this.options.toleranceMs);
118
+ return {
119
+ event: verified.event,
120
+ id: verified.eventId,
121
+ timestamp: new Date(verified.timestamp),
122
+ payload: verified.payload,
123
+ metadata: _nullishCoalesce(verified.metadata, () => ( null)),
124
+ connection: _nullishCoalesce(verified.connection, () => ( null)),
125
+ isTest: verified.isTest
126
+ };
127
+ } catch (error) {
128
+ throw toOneError(error);
129
+ }
130
+ }
131
+ /**
132
+ * Verifies, parses, and dispatches a delivery to every handler registered for
133
+ * its event type, then to the catch-all handlers. Handlers run sequentially
134
+ * and are awaited.
135
+ */
136
+ async handle(rawBody, signature) {
137
+ const delivery = this.verify(rawBody, signature);
138
+ const accepts = (registered) => registered.connection === null || registered.connection === delivery.connection;
139
+ let failure;
140
+ const run = async (registered) => {
141
+ try {
142
+ await registered.run(delivery);
143
+ } catch (error) {
144
+ failure ??= { error };
145
+ }
146
+ };
147
+ if (!delivery.isTest) {
148
+ for (const registered of (_nullishCoalesce(this.handlers.get(delivery.event), () => ( []))).filter(accepts)) {
149
+ await run(registered);
150
+ }
151
+ }
152
+ for (const registered of this.anyHandlers.filter(accepts)) {
153
+ await run(registered);
154
+ }
155
+ if (failure) throw failure.error;
156
+ return delivery;
157
+ }
158
+ /**
159
+ * Registers this listener with One under the stable name `key`, pointing at
160
+ * `url` and subscribing to exactly the events handlers were attached for.
161
+ *
162
+ * Idempotent: calling it on every boot reconciles the one listener named
163
+ * `key` rather than accumulating duplicates.
164
+ */
165
+ async listen(key, url) {
166
+ return this.client.registerWebhook(key, url, this.events(), this.options.secret);
167
+ }
168
+ }, _class);
169
+ var ConnectionWebhooksBase = (_class2 = class {
170
+ constructor(key) {;_class2.prototype.__init3.call(this);_class2.prototype.__init4.call(this);
171
+ this.key = key;
172
+ }
173
+
174
+ __init3() {this.handlers = /* @__PURE__ */ new Map()}
175
+ __init4() {this.anyHandlers = []}
176
+ /** @internal Registers a typed handler; generated methods wrap this. */
177
+ register(event, run) {
178
+ const existing = _nullishCoalesce(this.handlers.get(event), () => ( []));
179
+ existing.push({ connection: this.key, run });
180
+ this.handlers.set(event, existing);
181
+ return this;
182
+ }
183
+ /** Registers a handler for every event concerning this connection. */
184
+ onAny(handler) {
185
+ this.anyHandlers.push({ connection: this.key, run: handler });
186
+ return this;
187
+ }
188
+ /** @internal Hands the collected handlers to the parent registry. */
189
+ drain() {
190
+ return this.handlers;
191
+ }
192
+ /** @internal Hands the collected catch-all handlers to the parent registry. */
193
+ drainAny() {
194
+ return this.anyHandlers;
195
+ }
196
+ }, _class2);
197
+
198
+ // src/webhooks.generated.ts
199
+ var ALL_WEBHOOK_EVENTS = [
200
+ "connection.created",
201
+ "connection.deleted",
202
+ "connection.oauth.created",
203
+ "member.added",
204
+ "member.removed",
205
+ "member.role_updated",
206
+ "oauth.failed",
207
+ "oauth.refreshed",
208
+ "organization.created",
209
+ "organization.deleted",
210
+ "organization.updated",
211
+ "passthrough.executed",
212
+ "project.created",
213
+ "project.deleted",
214
+ "project.updated"
215
+ ];
216
+ var CONNECTION_SCOPED_EVENTS = [
217
+ "connection.created",
218
+ "connection.deleted",
219
+ "connection.oauth.created",
220
+ "oauth.failed",
221
+ "oauth.refreshed",
222
+ "passthrough.executed"
223
+ ];
224
+ var Webhooks = class extends WebhooksBase {
225
+ /** Scopes to the generated connection registry, so a `connection(..)` block
226
+ * offers the typed per-event methods rather than the bare base. */
227
+ scopeConstructor() {
228
+ return ConnectionWebhooks;
229
+ }
230
+ /** The full catalog, so an unscoped catch-all subscribes to everything. */
231
+ catalog() {
232
+ return ALL_WEBHOOK_EVENTS;
233
+ }
234
+ /** The connection-carrying subset, for a catch-all scoped to a connection. */
235
+ connectionCatalog() {
236
+ return CONNECTION_SCOPED_EVENTS;
237
+ }
238
+ /** Narrows the block's scope to the typed registry. */
239
+ connection(key, block) {
240
+ return super.connection(key, block);
241
+ }
242
+ /** Registers a handler for `connection.created`. */
243
+ connectionCreated(handler) {
244
+ return this.register("connection.created", null, handler);
245
+ }
246
+ /** Registers a handler for `connection.deleted`. */
247
+ connectionDeleted(handler) {
248
+ return this.register("connection.deleted", null, handler);
249
+ }
250
+ /** Registers a handler for `connection.oauth.created`. */
251
+ connectionOauthCreated(handler) {
252
+ return this.register("connection.oauth.created", null, handler);
253
+ }
254
+ /** Registers a handler for `member.added`. */
255
+ memberAdded(handler) {
256
+ return this.register("member.added", null, handler);
257
+ }
258
+ /** Registers a handler for `member.removed`. */
259
+ memberRemoved(handler) {
260
+ return this.register("member.removed", null, handler);
261
+ }
262
+ /** Registers a handler for `member.role_updated`. */
263
+ memberRoleUpdated(handler) {
264
+ return this.register("member.role_updated", null, handler);
265
+ }
266
+ /** Registers a handler for `oauth.failed`. */
267
+ oauthFailed(handler) {
268
+ return this.register("oauth.failed", null, handler);
269
+ }
270
+ /** Registers a handler for `oauth.refreshed`. */
271
+ oauthRefreshed(handler) {
272
+ return this.register("oauth.refreshed", null, handler);
273
+ }
274
+ /** Registers a handler for `organization.created`. */
275
+ organizationCreated(handler) {
276
+ return this.register("organization.created", null, handler);
277
+ }
278
+ /** Registers a handler for `organization.deleted`. */
279
+ organizationDeleted(handler) {
280
+ return this.register("organization.deleted", null, handler);
281
+ }
282
+ /** Registers a handler for `organization.updated`. */
283
+ organizationUpdated(handler) {
284
+ return this.register("organization.updated", null, handler);
285
+ }
286
+ /** Registers a handler for `passthrough.executed`. */
287
+ passthroughExecuted(handler) {
288
+ return this.register("passthrough.executed", null, handler);
289
+ }
290
+ /** Registers a handler for `project.created`. */
291
+ projectCreated(handler) {
292
+ return this.register("project.created", null, handler);
293
+ }
294
+ /** Registers a handler for `project.deleted`. */
295
+ projectDeleted(handler) {
296
+ return this.register("project.deleted", null, handler);
297
+ }
298
+ /** Registers a handler for `project.updated`. */
299
+ projectUpdated(handler) {
300
+ return this.register("project.updated", null, handler);
301
+ }
302
+ };
303
+ var ConnectionWebhooks = class extends ConnectionWebhooksBase {
304
+ /** Registers a handler for `connection.created` on this connection. */
305
+ connectionCreated(handler) {
306
+ return this.register("connection.created", handler);
307
+ }
308
+ /** Registers a handler for `connection.deleted` on this connection. */
309
+ connectionDeleted(handler) {
310
+ return this.register("connection.deleted", handler);
311
+ }
312
+ /** Registers a handler for `connection.oauth.created` on this connection. */
313
+ connectionOauthCreated(handler) {
314
+ return this.register("connection.oauth.created", handler);
315
+ }
316
+ /** Registers a handler for `oauth.failed` on this connection. */
317
+ oauthFailed(handler) {
318
+ return this.register("oauth.failed", handler);
319
+ }
320
+ /** Registers a handler for `oauth.refreshed` on this connection. */
321
+ oauthRefreshed(handler) {
322
+ return this.register("oauth.refreshed", handler);
323
+ }
324
+ /** Registers a handler for `passthrough.executed` on this connection. */
325
+ passthroughExecuted(handler) {
326
+ return this.register("passthrough.executed", handler);
327
+ }
328
+ };
329
+
330
+ // src/client.ts
331
+ var CallLifecycle = class {
332
+ constructor(hooks) {
333
+ this.hooks = hooks;
334
+ }
335
+
336
+ async execute(call, complete) {
337
+ try {
338
+ const completed = complete(await call());
339
+ _optionalChain([this, 'access', _ => _.hooks, 'access', _2 => _2.onSuccess, 'optionalCall', _3 => _3(completed.result)]);
340
+ return completed.output;
341
+ } catch (error) {
342
+ const err = toOneError(error);
343
+ _optionalChain([this, 'access', _4 => _4.hooks, 'access', _5 => _5.onError, 'optionalCall', _6 => _6(err)]);
344
+ throw err;
345
+ }
346
+ }
347
+ };
7
348
  var One = class _One {
8
349
 
9
350
 
@@ -14,7 +355,7 @@ var One = class _One {
14
355
  } catch (error) {
15
356
  throw toOneError(error);
16
357
  }
17
- this.hooks = { onSuccess, onError };
358
+ this.lifecycle = new CallLifecycle({ onSuccess, onError });
18
359
  }
19
360
  /** Creates a client from the environment (`ONE_SECRET`, `ONE_BASE_URL`). */
20
361
  static fromEnv() {
@@ -25,19 +366,36 @@ var One = class _One {
25
366
  } catch (error) {
26
367
  throw toOneError(error);
27
368
  }
28
- fields.hooks = {};
369
+ fields.lifecycle = new CallLifecycle({});
29
370
  return client;
30
371
  }
31
372
  /** Scopes subsequent calls to a connection by its key. */
32
373
  connection(key) {
33
- return new ConnectionScope(this.native, key, this.hooks);
374
+ return new ConnectionScope(this.native, key, this.lifecycle);
375
+ }
376
+ /**
377
+ * Starts building a webhook listener, verified with the subscription's
378
+ * signing secret.
379
+ */
380
+ webhooks(options) {
381
+ return new Webhooks(this, options);
382
+ }
383
+ /** @internal Registers a webhook listener; the route and request shape live in Rust. */
384
+ async registerWebhook(key, url, events, secret) {
385
+ return this.lifecycle.execute(
386
+ () => this.native.registerWebhook(key, url, events, secret),
387
+ (result) => {
388
+ const out = new CallResult(result.status, result.headers, result.data);
389
+ return { output: result.data, result: out };
390
+ }
391
+ );
34
392
  }
35
393
  };
36
394
  var ConnectionScope = class {
37
- constructor(native, key, hooks) {
395
+ constructor(native, key, lifecycle) {
38
396
  this.native = native;
39
397
  this.key = key;
40
- this.hooks = hooks;
398
+ this.lifecycle = lifecycle;
41
399
  }
42
400
 
43
401
 
@@ -56,16 +414,13 @@ var ConnectionScope = class {
56
414
  return this.execute({ connectionKey: this.key, ...request }, options);
57
415
  }
58
416
  async execute(request, options) {
59
- try {
60
- const result = await this.native.run({ ...request, ..._nullishCoalesce(options, () => ( {})) });
61
- const out = new CallResult(result.status, result.headers, result.data);
62
- _optionalChain([this, 'access', _ => _.hooks, 'access', _2 => _2.onSuccess, 'optionalCall', _3 => _3(out)]);
63
- return out;
64
- } catch (error) {
65
- const err = toOneError(error);
66
- _optionalChain([this, 'access', _4 => _4.hooks, 'access', _5 => _5.onError, 'optionalCall', _6 => _6(err)]);
67
- throw err;
68
- }
417
+ return this.lifecycle.execute(
418
+ () => this.native.run({ ...request, ..._nullishCoalesce(options, () => ( {})) }),
419
+ (result) => {
420
+ const out = new CallResult(result.status, result.headers, result.data);
421
+ return { output: out, result: out };
422
+ }
423
+ );
69
424
  }
70
425
  };
71
426
  var CallResult = class {
@@ -82,33 +437,12 @@ var CallResult = class {
82
437
  return this.data;
83
438
  }
84
439
  };
85
- var OneError = class extends Error {
86
- constructor(code, message, status, body, retryable) {
87
- super(message);
88
- this.code = code;
89
- this.status = status;
90
- this.body = body;
91
- this.retryable = retryable;
92
- this.name = "OneError";
93
- }
94
-
95
-
96
-
97
-
98
- };
99
- function toOneError(error) {
100
- const message = error instanceof Error ? error.message : String(error);
101
- try {
102
- const envelope = JSON.parse(message);
103
- return new OneError(envelope.code, envelope.message, envelope.status, envelope.body, envelope.retryable);
104
- } catch (e) {
105
- return new OneError("unknown", message, void 0, void 0, false);
106
- }
107
- }
108
440
 
109
441
 
110
442
 
111
443
 
112
444
 
113
445
 
114
- exports.Action = _chunkKPQGG74Ujs.Action; exports.CallResult = CallResult; exports.ConnectionScope = ConnectionScope; exports.One = One; exports.OneError = OneError;
446
+
447
+
448
+ exports.Action = _chunkKPQGG74Ujs.Action; exports.CallResult = CallResult; exports.ConnectionScope = ConnectionScope; exports.ConnectionWebhooks = ConnectionWebhooks; exports.One = One; exports.OneError = OneError; exports.Webhooks = Webhooks;