@geekmidas/events 10.0.0-alpha.16 → 10.0.0-alpha.161
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/README.md +65 -1
- package/dist/{SQSSubscriber-BXLE_1L3.mjs → SQSSubscriber-BEJBfNTe.mjs} +94 -10
- package/dist/SQSSubscriber-BEJBfNTe.mjs.map +1 -0
- package/dist/{SQSSubscriber-DtRUaZB3.cjs → SQSSubscriber-COTqWvOk.cjs} +101 -10
- package/dist/SQSSubscriber-COTqWvOk.cjs.map +1 -0
- package/dist/basic/index.cjs +35 -4
- package/dist/basic/index.cjs.map +1 -1
- package/dist/basic/index.d.cts +8 -1
- package/dist/basic/index.d.cts.map +1 -1
- package/dist/basic/index.d.mts +8 -1
- package/dist/basic/index.d.mts.map +1 -1
- package/dist/basic/index.mjs +35 -5
- package/dist/basic/index.mjs.map +1 -1
- package/dist/index.cjs +45 -142
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +80 -20
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +80 -20
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +33 -141
- package/dist/index.mjs.map +1 -1
- package/dist/pgboss/index.cjs +121 -34
- package/dist/pgboss/index.cjs.map +1 -1
- package/dist/pgboss/index.d.cts +45 -4
- package/dist/pgboss/index.d.cts.map +1 -1
- package/dist/pgboss/index.d.mts +45 -4
- package/dist/pgboss/index.d.mts.map +1 -1
- package/dist/pgboss/index.mjs +119 -34
- package/dist/pgboss/index.mjs.map +1 -1
- package/dist/rabbitmq/index.cjs +60 -27
- package/dist/rabbitmq/index.cjs.map +1 -1
- package/dist/rabbitmq/index.d.cts +9 -1
- package/dist/rabbitmq/index.d.cts.map +1 -1
- package/dist/rabbitmq/index.d.mts +9 -1
- package/dist/rabbitmq/index.d.mts.map +1 -1
- package/dist/rabbitmq/index.mjs +61 -27
- package/dist/rabbitmq/index.mjs.map +1 -1
- package/dist/{types-gGaoT8qc.d.cts → registry-DIx25Q5s.d.cts} +108 -2
- package/dist/registry-DIx25Q5s.d.cts.map +1 -0
- package/dist/{types-gGaoT8qc.d.mts → registry-DIx25Q5s.d.mts} +108 -2
- package/dist/registry-DIx25Q5s.d.mts.map +1 -0
- package/dist/registry-DXLY1Xf6.mjs +99 -0
- package/dist/registry-DXLY1Xf6.mjs.map +1 -0
- package/dist/registry-DlT36229.cjs +122 -0
- package/dist/registry-DlT36229.cjs.map +1 -0
- package/dist/sns/index.cjs +249 -11
- package/dist/sns/index.cjs.map +1 -1
- package/dist/sns/index.d.cts +145 -8
- package/dist/sns/index.d.cts.map +1 -1
- package/dist/sns/index.d.mts +145 -8
- package/dist/sns/index.d.mts.map +1 -1
- package/dist/sns/index.mjs +234 -12
- package/dist/sns/index.mjs.map +1 -1
- package/dist/sns/message.cjs +194 -0
- package/dist/sns/message.cjs.map +1 -0
- package/dist/sns/message.d.cts +127 -0
- package/dist/sns/message.d.cts.map +1 -0
- package/dist/sns/message.d.mts +127 -0
- package/dist/sns/message.d.mts.map +1 -0
- package/dist/sns/message.mjs +182 -0
- package/dist/sns/message.mjs.map +1 -0
- package/dist/sqs/index.cjs +22 -66
- package/dist/sqs/index.cjs.map +1 -1
- package/dist/sqs/index.d.cts +10 -1
- package/dist/sqs/index.d.cts.map +1 -1
- package/dist/sqs/index.d.mts +10 -1
- package/dist/sqs/index.d.mts.map +1 -1
- package/dist/sqs/index.mjs +20 -63
- package/dist/sqs/index.mjs.map +1 -1
- package/dist/telemetry-DG3l807O.cjs +309 -0
- package/dist/telemetry-DG3l807O.cjs.map +1 -0
- package/dist/telemetry-DjjgJMul.mjs +244 -0
- package/dist/telemetry-DjjgJMul.mjs.map +1 -0
- package/package.json +18 -3
- package/dist/PgBossConnection-CywKoAZU.cjs +0 -2
- package/dist/PgBossConnection-DjoqT84r.mjs +0 -2
- package/dist/RabbitMQConnection-C9eccBL8.cjs +0 -2
- package/dist/RabbitMQConnection-CAp7VqyT.mjs +0 -2
- package/dist/SNSConnection-BWDC1wAF.cjs +0 -2
- package/dist/SNSConnection-ezQvVrDv.mjs +0 -2
- package/dist/SQSSubscriber-BXLE_1L3.mjs.map +0 -1
- package/dist/SQSSubscriber-DtRUaZB3.cjs.map +0 -1
- package/dist/types-BcZjLxVV.cjs +0 -51
- package/dist/types-BcZjLxVV.cjs.map +0 -1
- package/dist/types-Bk5JM6MP.mjs +0 -40
- package/dist/types-Bk5JM6MP.mjs.map +0 -1
- package/dist/types-gGaoT8qc.d.cts.map +0 -1
- package/dist/types-gGaoT8qc.d.mts.map +0 -1
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
const require_telemetry = require("./telemetry-DG3l807O.cjs");
|
|
2
|
+
//#region src/registry.ts
|
|
3
|
+
/**
|
|
4
|
+
* Where each built-in driver lives, so a missing one can be named exactly —
|
|
5
|
+
* the subpath to import and the export to register.
|
|
6
|
+
*/
|
|
7
|
+
const BUILT_IN = {
|
|
8
|
+
["basic"]: {
|
|
9
|
+
subpath: "@geekmidas/events/basic",
|
|
10
|
+
driver: "basicEventsDriver"
|
|
11
|
+
},
|
|
12
|
+
["pgboss"]: {
|
|
13
|
+
subpath: "@geekmidas/events/pgboss",
|
|
14
|
+
driver: "pgbossEventsDriver"
|
|
15
|
+
},
|
|
16
|
+
["sns"]: {
|
|
17
|
+
subpath: "@geekmidas/events/sns",
|
|
18
|
+
driver: "snsEventsDriver"
|
|
19
|
+
},
|
|
20
|
+
["sqs"]: {
|
|
21
|
+
subpath: "@geekmidas/events/sqs",
|
|
22
|
+
driver: "sqsEventsDriver"
|
|
23
|
+
},
|
|
24
|
+
["rabbitmq"]: {
|
|
25
|
+
subpath: "@geekmidas/events/rabbitmq",
|
|
26
|
+
driver: "rabbitmqEventsDriver"
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The registry lives on `globalThis`, so one registration is seen by every
|
|
31
|
+
* copy of this module — the ESM and the CJS build of one install, which a
|
|
32
|
+
* process can load side by side, as `Credentials` already has to allow for.
|
|
33
|
+
*/
|
|
34
|
+
const REGISTRY = Symbol.for("@geekmidas/events/drivers");
|
|
35
|
+
function drivers() {
|
|
36
|
+
const global = globalThis;
|
|
37
|
+
global[REGISTRY] ??= /* @__PURE__ */ new Map();
|
|
38
|
+
return global[REGISTRY];
|
|
39
|
+
}
|
|
40
|
+
/** Make a driver available to `Publisher`, `Subscriber` and friends. Idempotent. */
|
|
41
|
+
function registerEventsDriver(driver) {
|
|
42
|
+
drivers().set(driver.scheme, driver);
|
|
43
|
+
}
|
|
44
|
+
/** Which schemes are currently registered — the useful half of a failure. */
|
|
45
|
+
function registeredEventsSchemes() {
|
|
46
|
+
return [...drivers().keys()].sort();
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The driver for a scheme — `'pgboss'`, `'pgboss:'`, or a whole connection
|
|
50
|
+
* string, whichever the caller has.
|
|
51
|
+
*
|
|
52
|
+
* @throws {UnregisteredEventsScheme} when the scheme is a broker this package
|
|
53
|
+
* implements but nothing registered its driver.
|
|
54
|
+
* @throws {UnsupportedEventTransport} when no broker here has that scheme.
|
|
55
|
+
*/
|
|
56
|
+
function eventsDriverFor(scheme, role = "connection") {
|
|
57
|
+
const name = schemeOf(scheme);
|
|
58
|
+
const driver = drivers().get(name);
|
|
59
|
+
if (driver) return driver;
|
|
60
|
+
if (BUILT_IN[name]) throw new UnregisteredEventsScheme(name, registeredEventsSchemes());
|
|
61
|
+
throw new require_telemetry.UnsupportedEventTransport(name, role);
|
|
62
|
+
}
|
|
63
|
+
/** `pgboss` from `pgboss`, `pgboss:` or `pgboss://…`. */
|
|
64
|
+
function schemeOf(value) {
|
|
65
|
+
const separator = value.indexOf(":");
|
|
66
|
+
return separator === -1 ? value : value.slice(0, separator);
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A connection string for a broker whose driver nothing registered.
|
|
70
|
+
*
|
|
71
|
+
* The broker exists — this is not a typo'd scheme — but the process was never
|
|
72
|
+
* told about it. Usually a script building its own publisher, or a build that
|
|
73
|
+
* registered the drivers for a different target than the one that composed
|
|
74
|
+
* the connection string.
|
|
75
|
+
*/
|
|
76
|
+
var UnregisteredEventsScheme = class extends Error {
|
|
77
|
+
scheme;
|
|
78
|
+
registered;
|
|
79
|
+
/** The subpath that exports the missing driver. */
|
|
80
|
+
subpath;
|
|
81
|
+
/** The driver's export name. */
|
|
82
|
+
driver;
|
|
83
|
+
constructor(scheme, registered) {
|
|
84
|
+
const { subpath, driver } = BUILT_IN[scheme] ?? {
|
|
85
|
+
subpath: `@geekmidas/events/${scheme}`,
|
|
86
|
+
driver: `${scheme}EventsDriver`
|
|
87
|
+
};
|
|
88
|
+
super(`No events driver is registered for '${scheme}://'. ` + (registered.length ? `Registered: ${registered.join(", ")}. ` : "Nothing is registered. ") + `Register it once where the process starts: import { registerEventsDriver } from '@geekmidas/events'; import { ${driver} } from '${subpath}'; registerEventsDriver(${driver});`);
|
|
89
|
+
this.scheme = scheme;
|
|
90
|
+
this.registered = registered;
|
|
91
|
+
this.name = "UnregisteredEventsScheme";
|
|
92
|
+
this.subpath = subpath;
|
|
93
|
+
this.driver = driver;
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
//#endregion
|
|
97
|
+
Object.defineProperty(exports, "UnregisteredEventsScheme", {
|
|
98
|
+
enumerable: true,
|
|
99
|
+
get: function() {
|
|
100
|
+
return UnregisteredEventsScheme;
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
Object.defineProperty(exports, "eventsDriverFor", {
|
|
104
|
+
enumerable: true,
|
|
105
|
+
get: function() {
|
|
106
|
+
return eventsDriverFor;
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
Object.defineProperty(exports, "registerEventsDriver", {
|
|
110
|
+
enumerable: true,
|
|
111
|
+
get: function() {
|
|
112
|
+
return registerEventsDriver;
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
Object.defineProperty(exports, "registeredEventsSchemes", {
|
|
116
|
+
enumerable: true,
|
|
117
|
+
get: function() {
|
|
118
|
+
return registeredEventsSchemes;
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=registry-DlT36229.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-DlT36229.cjs","names":["UnsupportedEventTransport"],"sources":["../src/registry.ts"],"sourcesContent":["/**\n * Events drivers, keyed by connection-string scheme.\n *\n * The same shape `@geekmidas/storage` and `@geekmidas/cache` use, for the same\n * reason: a topic or a queue is handed one connection string, and the scheme in\n * it (`pgboss://`, `sns://`, …) picks the broker. Which brokers exist is the\n * entry point's decision — a generated server registering pg-boss, a Lambda\n * registering SNS and SQS — so a bundle only ever contains the broker its\n * target uses, and never resolves the others' optional peer dependencies.\n *\n * Registration is explicit rather than an import side effect, because a\n * side-effecting module is exactly what a bundler is entitled to drop.\n */\n\nimport type { PublisherOptions } from './Publisher';\nimport type {\n\tEventConnection,\n\tEventPublisher,\n\tEventSubscriber,\n\tPublishableMessage,\n} from './types';\nimport { EventPublisherType, UnsupportedEventTransport } from './types';\n\ntype AnyMessage = PublishableMessage<string, any>;\n\n/** How a subscriber built from a connection is used, beyond its address. */\nexport interface SubscriberOptions {\n\t/**\n\t * The topic subscribed to. pg-boss needs it, with {@link subscription}, to\n\t * give each subscriber a queue of its own; the other brokers carry the topic\n\t * in their address and ignore it.\n\t */\n\ttopic?: string;\n\t/** The subscriber's name — its own queue on pg-boss. */\n\tsubscription?: string;\n}\n\n/**\n * One broker: the connections, publishers and subscribers for its scheme.\n *\n * A driver owns parsing — the shape of an `sns://` string is SNS's business —\n * and is the only module that imports its broker's client library.\n */\nexport interface EventsDriver {\n\t/**\n\t * The scheme this driver handles, without the colon — `'pgboss'`, `'sns'`.\n\t * It is also the `type` of every connection the driver builds, which is how\n\t * a connection finds its way back here.\n\t */\n\treadonly scheme: `${EventPublisherType}`;\n\t/** A connection, connected, for a connection string. */\n\tconnect(connectionString: string): Promise<EventConnection>;\n\t/** A publisher, with a connection of its own, for a connection string. */\n\tpublisher<TMessage extends AnyMessage>(\n\t\tconnectionString: string,\n\t\toptions: PublisherOptions,\n\t): Promise<EventPublisher<TMessage>>;\n\t/** A publisher on a connection this driver built. */\n\tpublisherFor<TMessage extends AnyMessage>(\n\t\tconnection: EventConnection,\n\t\toptions: PublisherOptions,\n\t): EventPublisher<TMessage>;\n\t/** A subscriber, with a connection of its own, for a connection string. */\n\tsubscriber<TMessage extends AnyMessage>(\n\t\tconnectionString: string,\n\t): Promise<EventSubscriber<TMessage>>;\n\t/** A subscriber on a connection this driver built. */\n\tsubscriberFor<TMessage extends AnyMessage>(\n\t\tconnection: EventConnection,\n\t\toptions: SubscriberOptions,\n\t): EventSubscriber<TMessage>;\n}\n\n/**\n * Where each built-in driver lives, so a missing one can be named exactly —\n * the subpath to import and the export to register.\n */\nconst BUILT_IN: Readonly<Record<string, { subpath: string; driver: string }>> =\n\t{\n\t\t[EventPublisherType.Basic]: {\n\t\t\tsubpath: '@geekmidas/events/basic',\n\t\t\tdriver: 'basicEventsDriver',\n\t\t},\n\t\t[EventPublisherType.PgBoss]: {\n\t\t\tsubpath: '@geekmidas/events/pgboss',\n\t\t\tdriver: 'pgbossEventsDriver',\n\t\t},\n\t\t[EventPublisherType.SNS]: {\n\t\t\tsubpath: '@geekmidas/events/sns',\n\t\t\tdriver: 'snsEventsDriver',\n\t\t},\n\t\t[EventPublisherType.SQS]: {\n\t\t\tsubpath: '@geekmidas/events/sqs',\n\t\t\tdriver: 'sqsEventsDriver',\n\t\t},\n\t\t[EventPublisherType.RabbitMQ]: {\n\t\t\tsubpath: '@geekmidas/events/rabbitmq',\n\t\t\tdriver: 'rabbitmqEventsDriver',\n\t\t},\n\t};\n\n/**\n * The registry lives on `globalThis`, so one registration is seen by every\n * copy of this module — the ESM and the CJS build of one install, which a\n * process can load side by side, as `Credentials` already has to allow for.\n */\nconst REGISTRY = Symbol.for('@geekmidas/events/drivers');\n\nfunction drivers(): Map<string, EventsDriver> {\n\tconst global = globalThis as { [REGISTRY]?: Map<string, EventsDriver> };\n\tglobal[REGISTRY] ??= new Map();\n\treturn global[REGISTRY];\n}\n\n/** Make a driver available to `Publisher`, `Subscriber` and friends. Idempotent. */\nexport function registerEventsDriver(driver: EventsDriver): void {\n\tdrivers().set(driver.scheme, driver);\n}\n\n/** Which schemes are currently registered — the useful half of a failure. */\nexport function registeredEventsSchemes(): string[] {\n\treturn [...drivers().keys()].sort();\n}\n\n/**\n * The driver for a scheme — `'pgboss'`, `'pgboss:'`, or a whole connection\n * string, whichever the caller has.\n *\n * @throws {UnregisteredEventsScheme} when the scheme is a broker this package\n * implements but nothing registered its driver.\n * @throws {UnsupportedEventTransport} when no broker here has that scheme.\n */\nexport function eventsDriverFor(\n\tscheme: string,\n\trole: 'publisher' | 'subscriber' | 'connection' = 'connection',\n): EventsDriver {\n\tconst name = schemeOf(scheme);\n\tconst driver = drivers().get(name);\n\tif (driver) return driver;\n\n\tif (BUILT_IN[name]) {\n\t\tthrow new UnregisteredEventsScheme(name, registeredEventsSchemes());\n\t}\n\tthrow new UnsupportedEventTransport(name, role);\n}\n\n/** `pgboss` from `pgboss`, `pgboss:` or `pgboss://…`. */\nfunction schemeOf(value: string): string {\n\tconst separator = value.indexOf(':');\n\treturn separator === -1 ? value : value.slice(0, separator);\n}\n\n/**\n * A connection string for a broker whose driver nothing registered.\n *\n * The broker exists — this is not a typo'd scheme — but the process was never\n * told about it. Usually a script building its own publisher, or a build that\n * registered the drivers for a different target than the one that composed\n * the connection string.\n */\nexport class UnregisteredEventsScheme extends Error {\n\t/** The subpath that exports the missing driver. */\n\treadonly subpath: string;\n\t/** The driver's export name. */\n\treadonly driver: string;\n\n\tconstructor(\n\t\t/** The scheme with no driver, without the colon — `'pgboss'`. */\n\t\treadonly scheme: string,\n\t\t/** What is registered, so the caller can see what was chosen instead. */\n\t\treadonly registered: readonly string[],\n\t) {\n\t\tconst { subpath, driver } = BUILT_IN[scheme] ?? {\n\t\t\tsubpath: `@geekmidas/events/${scheme}`,\n\t\t\tdriver: `${scheme}EventsDriver`,\n\t\t};\n\t\tsuper(\n\t\t\t`No events driver is registered for '${scheme}://'. ` +\n\t\t\t\t(registered.length\n\t\t\t\t\t? `Registered: ${registered.join(', ')}. `\n\t\t\t\t\t: 'Nothing is registered. ') +\n\t\t\t\t`Register it once where the process starts: ` +\n\t\t\t\t`import { registerEventsDriver } from '@geekmidas/events'; ` +\n\t\t\t\t`import { ${driver} } from '${subpath}'; ` +\n\t\t\t\t`registerEventsDriver(${driver});`,\n\t\t);\n\t\tthis.name = 'UnregisteredEventsScheme';\n\t\tthis.subpath = subpath;\n\t\tthis.driver = driver;\n\t}\n}\n"],"mappings":";;;;;;AA6EA,MAAM,WACL;EAC6B,UAAA;EAC3B,SAAS;EACT,QAAQ;CACT;EAC6B,WAAA;EAC5B,SAAS;EACT,QAAQ;CACT;EAC0B,QAAA;EACzB,SAAS;EACT,QAAQ;CACT;EAC0B,QAAA;EACzB,SAAS;EACT,QAAQ;CACT;EAC+B,aAAA;EAC9B,SAAS;EACT,QAAQ;CACT;AACD;;;;;;AAOD,MAAM,WAAW,OAAO,IAAI,2BAA2B;AAEvD,SAAS,UAAqC;CAC7C,MAAM,SAAS;CACf,OAAO,8BAAc,IAAI,IAAI;CAC7B,OAAO,OAAO;AACf;;AAGA,SAAgB,qBAAqB,QAA4B;CAChE,QAAQ,CAAC,CAAC,IAAI,OAAO,QAAQ,MAAM;AACpC;;AAGA,SAAgB,0BAAoC;CACnD,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK;AACnC;;;;;;;;;AAUA,SAAgB,gBACf,QACA,OAAkD,cACnC;CACf,MAAM,OAAO,SAAS,MAAM;CAC5B,MAAM,SAAS,QAAQ,CAAC,CAAC,IAAI,IAAI;CACjC,IAAI,QAAQ,OAAO;CAEnB,IAAI,SAAS,OACZ,MAAM,IAAI,yBAAyB,MAAM,wBAAwB,CAAC;CAEnE,MAAM,IAAIA,kBAAAA,0BAA0B,MAAM,IAAI;AAC/C;;AAGA,SAAS,SAAS,OAAuB;CACxC,MAAM,YAAY,MAAM,QAAQ,GAAG;CACnC,OAAO,cAAc,KAAK,QAAQ,MAAM,MAAM,GAAG,SAAS;AAC3D;;;;;;;;;AAUA,IAAa,2BAAb,cAA8C,MAAM;CAQzC;CAEA;;CARV;;CAEA;CAEA,YAEC,QAEA,YACC;EACD,MAAM,EAAE,SAAS,WAAW,SAAS,WAAW;GAC/C,SAAS,qBAAqB;GAC9B,QAAQ,GAAG,OAAO;EACnB;EACA,MACC,uCAAuC,OAAO,WAC5C,WAAW,SACT,eAAe,WAAW,KAAK,IAAI,EAAE,MACrC,6BACH,iHAEY,OAAO,WAAW,QAAQ,0BACd,OAAO,GACjC;EAjBS,KAAA,SAAA;EAEA,KAAA,aAAA;EAgBT,KAAK,OAAO;EACZ,KAAK,UAAU;EACf,KAAK,SAAS;CACf;AACD"}
|
package/dist/sns/index.cjs
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
require("../
|
|
3
|
-
const
|
|
2
|
+
const require_rolldown_runtime = require("../rolldown-runtime-C0BPl7ul.cjs");
|
|
3
|
+
const require_telemetry = require("../telemetry-DG3l807O.cjs");
|
|
4
|
+
const require_SQSSubscriber = require("../SQSSubscriber-COTqWvOk.cjs");
|
|
4
5
|
const require_sns_snsUrl = require("./snsUrl.cjs");
|
|
6
|
+
const require_sns_message = require("./message.cjs");
|
|
5
7
|
let _aws_sdk_client_sqs = require("@aws-sdk/client-sqs");
|
|
6
8
|
let _aws_sdk_client_sns = require("@aws-sdk/client-sns");
|
|
7
9
|
//#region src/sns/SNSConnection.ts
|
|
10
|
+
var SNSConnection_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({ SNSConnection: () => SNSConnection });
|
|
8
11
|
var SNSConnection = class SNSConnection {
|
|
9
12
|
type = "sns";
|
|
10
13
|
client;
|
|
@@ -77,26 +80,35 @@ var SNSPublisher = class SNSPublisher {
|
|
|
77
80
|
* Format: sns://?topicArn=arn:aws:sns:region:account:topic®ion=us-east-1&endpoint=http://localhost:4566
|
|
78
81
|
*/
|
|
79
82
|
static async fromConnectionString(connectionString) {
|
|
80
|
-
const { SNSConnection } = await Promise.resolve().then(() =>
|
|
83
|
+
const { SNSConnection } = await Promise.resolve().then(() => SNSConnection_exports);
|
|
81
84
|
const connection = await SNSConnection.fromConnectionString(connectionString);
|
|
82
85
|
return new SNSPublisher(connection);
|
|
83
86
|
}
|
|
84
87
|
async publish(messages) {
|
|
85
88
|
if (messages.length === 0) return;
|
|
86
89
|
if (!this.connection.isConnected()) await this.connection.connect();
|
|
87
|
-
|
|
90
|
+
const topicArn = this.connection.topicArn;
|
|
91
|
+
const destination = topicArn.split(":").pop() ?? topicArn;
|
|
92
|
+
await require_telemetry.publishTraced(messages, (message) => ({
|
|
93
|
+
system: "aws_sns",
|
|
94
|
+
destination,
|
|
95
|
+
type: message.type
|
|
96
|
+
}), (carriers) => Promise.all(messages.map((message, i) => this.publishMessage(message, carriers[i]))));
|
|
88
97
|
}
|
|
89
|
-
async publishMessage(message) {
|
|
98
|
+
async publishMessage(message, carrier) {
|
|
90
99
|
const command = new _aws_sdk_client_sns.PublishCommand({
|
|
91
100
|
TopicArn: this.connection.topicArn,
|
|
92
101
|
Message: JSON.stringify({
|
|
93
102
|
type: message.type,
|
|
94
103
|
payload: message.payload
|
|
95
104
|
}),
|
|
96
|
-
MessageAttributes: {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
105
|
+
MessageAttributes: {
|
|
106
|
+
type: {
|
|
107
|
+
DataType: "String",
|
|
108
|
+
StringValue: message.type
|
|
109
|
+
},
|
|
110
|
+
...require_telemetry.carrierAsAttributes(carrier)
|
|
111
|
+
}
|
|
100
112
|
});
|
|
101
113
|
await this.connection.snsClient.send(command);
|
|
102
114
|
}
|
|
@@ -150,7 +162,7 @@ var SNSSubscriber = class SNSSubscriber {
|
|
|
150
162
|
*/
|
|
151
163
|
static async fromConnectionString(connectionString) {
|
|
152
164
|
const params = new URL(connectionString).searchParams;
|
|
153
|
-
const { SNSConnection } = await Promise.resolve().then(() =>
|
|
165
|
+
const { SNSConnection } = await Promise.resolve().then(() => SNSConnection_exports);
|
|
154
166
|
const connection = await SNSConnection.fromConnectionString(connectionString);
|
|
155
167
|
const options = {
|
|
156
168
|
queueName: params.get("queueName") || void 0,
|
|
@@ -246,16 +258,242 @@ var SnsQueueMissing = class extends Error {
|
|
|
246
258
|
}
|
|
247
259
|
};
|
|
248
260
|
//#endregion
|
|
261
|
+
//#region src/sns/driver.ts
|
|
262
|
+
/**
|
|
263
|
+
* `sns://` — an SNS topic, consumed through an SQS queue subscribed to it.
|
|
264
|
+
* Register it with `registerEventsDriver(snsEventsDriver)`; an AWS entry
|
|
265
|
+
* registers `sqsEventsDriver` beside it.
|
|
266
|
+
*/
|
|
267
|
+
const snsEventsDriver = {
|
|
268
|
+
scheme: "sns",
|
|
269
|
+
connect: (url) => SNSConnection.fromConnectionString(url),
|
|
270
|
+
publisher: (url) => SNSPublisher.fromConnectionString(url),
|
|
271
|
+
publisherFor: (connection) => new SNSPublisher(connection),
|
|
272
|
+
subscriber: (url) => SNSSubscriber.fromConnectionString(url),
|
|
273
|
+
subscriberFor: (connection) => new SNSSubscriber(connection)
|
|
274
|
+
};
|
|
275
|
+
//#endregion
|
|
276
|
+
//#region src/sns/push.ts
|
|
277
|
+
/** The subscription attributes a filter asks for, as SNS spells them. */
|
|
278
|
+
function subscriptionAttributes(filter) {
|
|
279
|
+
const attributes = filter.filterPolicy ? {
|
|
280
|
+
FilterPolicyScope: filter.filterPolicyScope ?? "MessageAttributes",
|
|
281
|
+
FilterPolicy: JSON.stringify(filter.filterPolicy)
|
|
282
|
+
} : filter.events ? {
|
|
283
|
+
FilterPolicyScope: "MessageAttributes",
|
|
284
|
+
FilterPolicy: JSON.stringify({ type: [...filter.events] })
|
|
285
|
+
} : {};
|
|
286
|
+
if (filter.deadLetterQueueArn) attributes.RedrivePolicy = JSON.stringify({ deadLetterTargetArn: filter.deadLetterQueueArn });
|
|
287
|
+
return attributes;
|
|
288
|
+
}
|
|
289
|
+
/** The protocol SNS delivers to an endpoint with, from its URL. */
|
|
290
|
+
function protocolOf(endpoint) {
|
|
291
|
+
const protocol = require_sns_message.parseUrl(endpoint)?.protocol.replace(":", "");
|
|
292
|
+
if (protocol !== "http" && protocol !== "https") throw new SnsEndpointNotHttp(endpoint);
|
|
293
|
+
return protocol;
|
|
294
|
+
}
|
|
295
|
+
/** Bring an existing subscription's attributes up to what is asked for. */
|
|
296
|
+
async function updateAttributes(connection, subscriptionArn, current, wanted) {
|
|
297
|
+
for (const [name, value] of Object.entries(wanted)) {
|
|
298
|
+
if (current[name] === value) continue;
|
|
299
|
+
await connection.snsClient.send(new _aws_sdk_client_sns.SetSubscriptionAttributesCommand({
|
|
300
|
+
SubscriptionArn: subscriptionArn,
|
|
301
|
+
AttributeName: name,
|
|
302
|
+
AttributeValue: value
|
|
303
|
+
}));
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Subscribe an HTTP endpoint to the connection's topic, converging on one
|
|
308
|
+
* confirmed subscription with the filter asked for — so it is safe on every
|
|
309
|
+
* start. What a server does against an emulator, where nothing deploys it;
|
|
310
|
+
* against SNS itself the deploy owns the subscription
|
|
311
|
+
* ({@link reconcileHttpSubscriptions}).
|
|
312
|
+
*
|
|
313
|
+
* - **none yet** — subscribed; SNS sends a confirmation to the endpoint.
|
|
314
|
+
* - **confirmed** — its filter and dead-letter queue are brought up to date.
|
|
315
|
+
* Subscribing again with different attributes is an error on SNS, and the
|
|
316
|
+
* events a subscriber names change.
|
|
317
|
+
* - **stuck pending** — a confirmation that never landed (the endpoint was
|
|
318
|
+
* down, or answered wrong). Subscribing the same endpoint again is a no-op
|
|
319
|
+
* on an emulator, so it is dropped and subscribed afresh, which sends a new
|
|
320
|
+
* confirmation.
|
|
321
|
+
*/
|
|
322
|
+
async function subscribeHttpEndpoint(connection, options) {
|
|
323
|
+
const protocol = protocolOf(options.endpoint);
|
|
324
|
+
const attributes = subscriptionAttributes(options);
|
|
325
|
+
const client = connection.snsClient;
|
|
326
|
+
const existing = (await topicSubscriptions(connection)).find((s) => s.endpoint === options.endpoint)?.arn;
|
|
327
|
+
if (existing) {
|
|
328
|
+
const { Attributes = {} } = await client.send(new _aws_sdk_client_sns.GetSubscriptionAttributesCommand({ SubscriptionArn: existing }));
|
|
329
|
+
if (Attributes.PendingConfirmation === "true") await client.send(new _aws_sdk_client_sns.UnsubscribeCommand({ SubscriptionArn: existing }));
|
|
330
|
+
else {
|
|
331
|
+
await updateAttributes(connection, existing, Attributes, attributes);
|
|
332
|
+
return existing;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const { SubscriptionArn } = await client.send(new _aws_sdk_client_sns.SubscribeCommand({
|
|
336
|
+
TopicArn: connection.topicArn,
|
|
337
|
+
Protocol: protocol,
|
|
338
|
+
Endpoint: options.endpoint,
|
|
339
|
+
Attributes: attributes,
|
|
340
|
+
ReturnSubscriptionArn: true
|
|
341
|
+
}));
|
|
342
|
+
return SubscriptionArn;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Converge a topic's HTTP subscriptions on the endpoints a deploy wants, and
|
|
346
|
+
* answer each one's ARN for the deploy to record and hand to the server.
|
|
347
|
+
*
|
|
348
|
+
* The deploy's half of push delivery against SNS itself: the server never
|
|
349
|
+
* subscribes, so its credentials need no `sns:Subscribe` — and the only
|
|
350
|
+
* subscriptions to the topic are ones the deploy made.
|
|
351
|
+
*
|
|
352
|
+
* Run it twice: once before the server starts, for the ARNs it is configured
|
|
353
|
+
* with — SNS answers one even while the subscription waits to be confirmed —
|
|
354
|
+
* and once the server is up, which subscribes each still-pending endpoint
|
|
355
|
+
* again so SNS resends its confirmation to a server now there to answer it.
|
|
356
|
+
* The ARN does not change between the two.
|
|
357
|
+
*
|
|
358
|
+
* - **absent** — subscribed with its filter.
|
|
359
|
+
* - **present** — its filter and dead-letter queue are brought up to date;
|
|
360
|
+
* pending, it is subscribed again to resend the confirmation.
|
|
361
|
+
* - **stale** — on {@link ReconcileHttpSubscriptionsOptions.ownedHost} and no
|
|
362
|
+
* longer wanted: unsubscribed. (A stale one SNS still lists as pending has
|
|
363
|
+
* no ARN to act on; SNS drops it unconfirmed after three days.)
|
|
364
|
+
*/
|
|
365
|
+
async function reconcileHttpSubscriptions(connection, options) {
|
|
366
|
+
const client = connection.snsClient;
|
|
367
|
+
const listed = await topicSubscriptions(connection);
|
|
368
|
+
const result = {
|
|
369
|
+
subscriptions: {},
|
|
370
|
+
pending: [],
|
|
371
|
+
removed: []
|
|
372
|
+
};
|
|
373
|
+
for (const spec of options.endpoints) {
|
|
374
|
+
const protocol = protocolOf(spec.endpoint);
|
|
375
|
+
const attributes = subscriptionAttributes(spec);
|
|
376
|
+
const subscribe = async () => (await client.send(new _aws_sdk_client_sns.SubscribeCommand({
|
|
377
|
+
TopicArn: connection.topicArn,
|
|
378
|
+
Protocol: protocol,
|
|
379
|
+
Endpoint: spec.endpoint,
|
|
380
|
+
Attributes: attributes,
|
|
381
|
+
ReturnSubscriptionArn: true
|
|
382
|
+
}))).SubscriptionArn;
|
|
383
|
+
const existing = listed.find((s) => s.endpoint === spec.endpoint)?.arn;
|
|
384
|
+
let arn;
|
|
385
|
+
let pending;
|
|
386
|
+
if (existing) {
|
|
387
|
+
const { Attributes = {} } = await client.send(new _aws_sdk_client_sns.GetSubscriptionAttributesCommand({ SubscriptionArn: existing }));
|
|
388
|
+
await updateAttributes(connection, existing, Attributes, attributes);
|
|
389
|
+
pending = Attributes.PendingConfirmation === "true";
|
|
390
|
+
arn = pending ? await subscribe() ?? existing : existing;
|
|
391
|
+
} else {
|
|
392
|
+
arn = await subscribe();
|
|
393
|
+
pending = true;
|
|
394
|
+
}
|
|
395
|
+
if (!arn) throw new SnsSubscriptionArnMissing(connection.topicArn, spec.endpoint);
|
|
396
|
+
result.subscriptions[spec.name] = arn;
|
|
397
|
+
if (pending) result.pending.push(spec.name);
|
|
398
|
+
}
|
|
399
|
+
const wanted = new Set(options.endpoints.map((spec) => spec.endpoint));
|
|
400
|
+
for (const { arn, endpoint } of listed) {
|
|
401
|
+
if (!arn || wanted.has(endpoint)) continue;
|
|
402
|
+
if (require_sns_message.parseUrl(endpoint)?.host !== options.ownedHost) continue;
|
|
403
|
+
await client.send(new _aws_sdk_client_sns.UnsubscribeCommand({ SubscriptionArn: arn }));
|
|
404
|
+
result.removed.push(arn);
|
|
405
|
+
}
|
|
406
|
+
return result;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Confirm a subscription through the API, as its topic's owner, rather than by
|
|
410
|
+
* visiting the URL SNS sent.
|
|
411
|
+
*
|
|
412
|
+
* `AuthenticateOnUnsubscribe` is the point of it. A subscription confirmed by
|
|
413
|
+
* visiting `SubscribeURL` can be removed by anyone holding the
|
|
414
|
+
* `UnsubscribeURL` every notification carries — one unauthenticated GET, and
|
|
415
|
+
* the endpoint is silently cut off. Confirmed this way, only the topic's owner
|
|
416
|
+
* can unsubscribe it. All it takes of the caller's credentials is
|
|
417
|
+
* `sns:ConfirmSubscription` on this one topic.
|
|
418
|
+
*/
|
|
419
|
+
async function confirmSubscription(connection, message) {
|
|
420
|
+
if (message.Type !== "SubscriptionConfirmation" || !message.Token) throw new require_sns_message.SnsNotAConfirmation(message.Type);
|
|
421
|
+
const { SubscriptionArn } = await connection.snsClient.send(new _aws_sdk_client_sns.ConfirmSubscriptionCommand({
|
|
422
|
+
TopicArn: message.TopicArn,
|
|
423
|
+
Token: message.Token,
|
|
424
|
+
AuthenticateOnUnsubscribe: "true"
|
|
425
|
+
}));
|
|
426
|
+
return SubscriptionArn;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Every subscription on the connection's topic, with the ARN SNS names for it
|
|
430
|
+
* — none for one real SNS lists as `PendingConfirmation`, which there is no
|
|
431
|
+
* ARN to act on (and which a new Subscribe resends the confirmation of anyway).
|
|
432
|
+
*/
|
|
433
|
+
async function topicSubscriptions(connection) {
|
|
434
|
+
const found = [];
|
|
435
|
+
let NextToken;
|
|
436
|
+
do {
|
|
437
|
+
const page = await connection.snsClient.send(new _aws_sdk_client_sns.ListSubscriptionsByTopicCommand({
|
|
438
|
+
TopicArn: connection.topicArn,
|
|
439
|
+
NextToken
|
|
440
|
+
}));
|
|
441
|
+
for (const s of page.Subscriptions ?? []) {
|
|
442
|
+
if (!s.Endpoint) continue;
|
|
443
|
+
found.push({
|
|
444
|
+
endpoint: s.Endpoint,
|
|
445
|
+
...s.SubscriptionArn?.startsWith("arn:") ? { arn: s.SubscriptionArn } : {}
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
NextToken = page.NextToken;
|
|
449
|
+
} while (NextToken);
|
|
450
|
+
return found;
|
|
451
|
+
}
|
|
452
|
+
var SnsEndpointNotHttp = class extends Error {
|
|
453
|
+
endpoint;
|
|
454
|
+
constructor(endpoint) {
|
|
455
|
+
super(`'${endpoint}' is not an http(s) URL. SNS pushes to an HTTP endpoint; subscribe a queue for anything else.`);
|
|
456
|
+
this.endpoint = endpoint;
|
|
457
|
+
this.name = "SnsEndpointNotHttp";
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
var SnsSubscriptionArnMissing = class extends Error {
|
|
461
|
+
topicArn;
|
|
462
|
+
endpoint;
|
|
463
|
+
constructor(topicArn, endpoint) {
|
|
464
|
+
super(`Subscribing '${endpoint}' to '${topicArn}' answered no subscription ARN, so there is nothing to record for the server to accept. Check the topic exists and the deploy may subscribe to it.`);
|
|
465
|
+
this.topicArn = topicArn;
|
|
466
|
+
this.endpoint = endpoint;
|
|
467
|
+
this.name = "SnsSubscriptionArnMissing";
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
//#endregion
|
|
249
471
|
exports.SNSConnection = SNSConnection;
|
|
250
|
-
exports.SNSConnection$1 = SNSConnection;
|
|
251
472
|
exports.SNSPublisher = SNSPublisher;
|
|
252
473
|
exports.SNSSubscriber = SNSSubscriber;
|
|
474
|
+
exports.SnsCertificateUnavailable = require_sns_message.SnsCertificateUnavailable;
|
|
475
|
+
exports.SnsCertificateUntrusted = require_sns_message.SnsCertificateUntrusted;
|
|
476
|
+
exports.SnsConfirmationFailed = require_sns_message.SnsConfirmationFailed;
|
|
477
|
+
exports.SnsEndpointNotHttp = SnsEndpointNotHttp;
|
|
478
|
+
exports.SnsMessageTypeUnknown = require_sns_message.SnsMessageTypeUnknown;
|
|
479
|
+
exports.SnsNotAConfirmation = require_sns_message.SnsNotAConfirmation;
|
|
253
480
|
exports.SnsQueueMissing = SnsQueueMissing;
|
|
481
|
+
exports.SnsSignatureInvalid = require_sns_message.SnsSignatureInvalid;
|
|
482
|
+
exports.SnsSignatureVersionUnknown = require_sns_message.SnsSignatureVersionUnknown;
|
|
483
|
+
exports.SnsSubscriptionArnMissing = SnsSubscriptionArnMissing;
|
|
484
|
+
exports.confirmSnsSubscription = require_sns_message.confirmSnsSubscription;
|
|
485
|
+
exports.confirmSubscription = confirmSubscription;
|
|
486
|
+
exports.reconcileHttpSubscriptions = reconcileHttpSubscriptions;
|
|
487
|
+
exports.snsEventsDriver = snsEventsDriver;
|
|
488
|
+
exports.snsStringToSign = require_sns_message.snsStringToSign;
|
|
254
489
|
Object.defineProperty(exports, "snsUrl", {
|
|
255
490
|
enumerable: true,
|
|
256
491
|
get: function() {
|
|
257
492
|
return require_sns_snsUrl.snsUrl_exports;
|
|
258
493
|
}
|
|
259
494
|
});
|
|
495
|
+
exports.subscribeHttpEndpoint = subscribeHttpEndpoint;
|
|
496
|
+
exports.toSnsEvent = require_sns_message.toSnsEvent;
|
|
497
|
+
exports.verifySnsMessage = require_sns_message.verifySnsMessage;
|
|
260
498
|
|
|
261
499
|
//# sourceMappingURL=index.cjs.map
|
package/dist/sns/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["SNSClient","PublishCommand","SQSClient","SQSConnection","SQSSubscriber","UnsubscribeCommand","DeleteQueueCommand","CreateQueueCommand","GetQueueAttributesCommand","SetQueueAttributesCommand","SubscribeCommand"],"sources":["../../src/sns/SNSConnection.ts","../../src/sns/SNSPublisher.ts","../../src/sns/SNSSubscriber.ts"],"sourcesContent":["import { SNSClient, type SNSClientConfig } from '@aws-sdk/client-sns';\nimport type { EventConnection } from '../types';\nimport { EventPublisherType } from '../types';\nimport * as snsUrl from './snsUrl';\n\nexport interface SNSConnectionConfig {\n\ttopicArn: string;\n\tregion?: string;\n\tendpoint?: string; // Custom endpoint (e.g., for LocalStack)\n\tcredentials?: {\n\t\taccessKeyId: string;\n\t\tsecretAccessKey: string;\n\t\tsessionToken?: string;\n\t};\n}\n\nexport class SNSConnection implements EventConnection {\n\treadonly type = EventPublisherType.SNS;\n\tprivate client: SNSClient;\n\tprivate connected = false;\n\tprivate config: SNSConnectionConfig;\n\n\tconstructor(config: SNSConnectionConfig) {\n\t\tthis.config = config;\n\n\t\tconst clientConfig: SNSClientConfig = {\n\t\t\tregion: config.region,\n\t\t\tendpoint: config.endpoint,\n\t\t\tcredentials: config.credentials,\n\t\t};\n\n\t\tthis.client = new SNSClient(clientConfig);\n\t}\n\n\t/**\n\t * Create an SNSConnection from a connection string\n\t * Format: sns://?topicArn=arn:aws:sns:region:account:topic®ion=us-east-1&endpoint=http://localhost:4566\n\t */\n\tstatic async fromConnectionString(\n\t\tconnectionString: string,\n\t): Promise<SNSConnection> {\n\t\t// Through the codec, not a second hand-rolled parse: the deploy target\n\t\t// composes these with `snsUrl.build`, and a string it cannot read back is\n\t\t// exactly the drift one shared module rules out.\n\t\tconst { topicArn, region, endpoint } = snsUrl.parse(connectionString);\n\t\tconst params = new URL(connectionString).searchParams;\n\n\t\tconst config: SNSConnectionConfig = {\n\t\t\ttopicArn,\n\t\t\tregion,\n\t\t\tendpoint,\n\t\t};\n\n\t\t// Credentials are not part of the address — see `snsUrl` — but a caller\n\t\t// may still pin them here, so they are read beside it rather than in it.\n\t\tconst accessKeyId = params.get('accessKeyId');\n\t\tconst secretAccessKey = params.get('secretAccessKey');\n\t\tif (accessKeyId && secretAccessKey) {\n\t\t\tconfig.credentials = {\n\t\t\t\taccessKeyId,\n\t\t\t\tsecretAccessKey,\n\t\t\t\tsessionToken: params.get('sessionToken') || undefined,\n\t\t\t};\n\t\t}\n\n\t\tconst connection = new SNSConnection(config);\n\t\tawait connection.connect();\n\t\treturn connection;\n\t}\n\n\tasync connect(): Promise<void> {\n\t\t// SNS doesn't have a traditional connection, but we mark as connected\n\t\tthis.connected = true;\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.client.destroy();\n\t\tthis.connected = false;\n\t}\n\n\tisConnected(): boolean {\n\t\treturn this.connected;\n\t}\n\n\t/**\n\t * Get the underlying SNS client\n\t */\n\tget snsClient(): SNSClient {\n\t\treturn this.client;\n\t}\n\n\t/**\n\t * Get the topic ARN for this connection\n\t */\n\tget topicArn(): string {\n\t\treturn this.config.topicArn;\n\t}\n}\n","import { PublishCommand } from '@aws-sdk/client-sns';\nimport type { EventPublisher, PublishableMessage } from '../types';\nimport type { SNSConnection } from './SNSConnection';\n\nexport type SNSPublisherOptions = {};\n\nexport class SNSPublisher<TMessage extends PublishableMessage<string, any>>\n\timplements EventPublisher<TMessage>\n{\n\tconstructor(\n\t\tprivate connection: SNSConnection,\n\t\t_options: SNSPublisherOptions = {},\n\t) {}\n\n\t/**\n\t * Create an SNSPublisher from a connection string\n\t * Format: sns://?topicArn=arn:aws:sns:region:account:topic®ion=us-east-1&endpoint=http://localhost:4566\n\t */\n\tstatic async fromConnectionString<\n\t\tTMessage extends PublishableMessage<string, any>,\n\t>(connectionString: string): Promise<SNSPublisher<TMessage>> {\n\t\tconst { SNSConnection } = await import('./SNSConnection');\n\t\tconst connection =\n\t\t\tawait SNSConnection.fromConnectionString(connectionString);\n\n\t\treturn new SNSPublisher<TMessage>(connection);\n\t}\n\n\tasync publish(messages: TMessage[]): Promise<void> {\n\t\tif (messages.length === 0) return;\n\n\t\tif (!this.connection.isConnected()) {\n\t\t\tawait this.connection.connect();\n\t\t}\n\n\t\t// Publish all messages\n\t\tawait Promise.all(messages.map((message) => this.publishMessage(message)));\n\t}\n\n\tprivate async publishMessage(message: TMessage): Promise<void> {\n\t\tconst command = new PublishCommand({\n\t\t\tTopicArn: this.connection.topicArn,\n\t\t\tMessage: JSON.stringify({\n\t\t\t\ttype: message.type,\n\t\t\t\tpayload: message.payload,\n\t\t\t}),\n\t\t\tMessageAttributes: {\n\t\t\t\ttype: {\n\t\t\t\t\tDataType: 'String',\n\t\t\t\t\tStringValue: message.type,\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\n\t\tawait this.connection.snsClient.send(command);\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// Publisher doesn't own the connection\n\t\t// Connection should be closed by whoever created it\n\t}\n}\n","import { SubscribeCommand, UnsubscribeCommand } from '@aws-sdk/client-sns';\nimport {\n\tCreateQueueCommand,\n\tDeleteQueueCommand,\n\tGetQueueAttributesCommand,\n\tSetQueueAttributesCommand,\n\tSQSClient,\n} from '@aws-sdk/client-sqs';\nimport { SQSConnection } from '../sqs/SQSConnection';\nimport { SQSSubscriber } from '../sqs/SQSSubscriber';\nimport type { EventSubscriber, PublishableMessage } from '../types';\nimport type { SNSConnection } from './SNSConnection';\n\nexport interface SNSSubscriberOptions {\n\tqueueName?: string; // Optional queue name (defaults to auto-generated)\n\tcreateQueue?: boolean; // Auto-create SQS queue (default: true)\n\tdeleteQueueOnClose?: boolean; // Delete queue when subscriber closes (default: false for named queues, true for auto-generated)\n\twaitTimeSeconds?: number; // SQS long polling (default: 20)\n\tmaxMessages?: number; // Max messages per poll (default: 10)\n}\n\n/**\n * SNS Subscriber - receives push-based messages from SNS via SQS queue\n *\n * Architecture:\n * SNS Topic → (push) → SQS Queue → Subscriber\n *\n * This subscriber automatically:\n * 1. Creates an SQS queue (or uses existing one)\n * 2. Subscribes the queue to the SNS topic\n * 3. Receives messages pushed from SNS to the queue\n * 4. Filters messages by topic ARN and message type\n * 5. Processes and acknowledges messages\n *\n * Note: While SQS long-polling is used internally to receive messages,\n * this is an implementation detail of the SNS push delivery mechanism.\n * Messages are pushed from SNS to SQS, and we receive those pushed messages.\n */\nexport class SNSSubscriber<TMessage extends PublishableMessage<string, any>>\n\timplements EventSubscriber<TMessage>\n{\n\tprivate sqsClient: SQSClient;\n\tprivate queueUrl?: string;\n\tprivate queueArn?: string;\n\tprivate subscriptionArn?: string;\n\tprivate sqsSubscriber?: SQSSubscriber<TMessage>;\n\tprivate options: Required<SNSSubscriberOptions>;\n\n\tconstructor(\n\t\tprivate connection: SNSConnection,\n\t\toptions: SNSSubscriberOptions = {},\n\t) {\n\t\tthis.options = {\n\t\t\tqueueName:\n\t\t\t\toptions.queueName ||\n\t\t\t\t`sns-sub-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n\t\t\tcreateQueue: options.createQueue ?? true,\n\t\t\tdeleteQueueOnClose: options.deleteQueueOnClose ?? !options.queueName, // Delete auto-generated queues\n\t\t\twaitTimeSeconds: options.waitTimeSeconds ?? 20,\n\t\t\tmaxMessages: options.maxMessages ?? 10,\n\t\t};\n\n\t\t// Create SQS client with same config as SNS\n\t\tthis.sqsClient = new SQSClient({\n\t\t\tregion: (this.connection as any).config.region,\n\t\t\tendpoint: (this.connection as any).config.endpoint,\n\t\t\tcredentials: (this.connection as any).config.credentials,\n\t\t});\n\t}\n\n\t/**\n\t * Create an SNSSubscriber from a connection string\n\t * Format: sns://?topicArn=...&queueName=myqueue®ion=us-east-1\n\t */\n\tstatic async fromConnectionString<\n\t\tTMessage extends PublishableMessage<string, any>,\n\t>(connectionString: string): Promise<SNSSubscriber<TMessage>> {\n\t\tconst url = new URL(connectionString);\n\t\tconst params = url.searchParams;\n\n\t\tconst { SNSConnection } = await import('./SNSConnection');\n\t\tconst connection =\n\t\t\tawait SNSConnection.fromConnectionString(connectionString);\n\n\t\tconst options: SNSSubscriberOptions = {\n\t\t\tqueueName: params.get('queueName') || undefined,\n\t\t\tcreateQueue: params.get('createQueue') !== 'false',\n\t\t\tdeleteQueueOnClose: params.get('deleteQueueOnClose') === 'true',\n\t\t\twaitTimeSeconds: params.get('waitTimeSeconds')\n\t\t\t\t? Number.parseInt(params.get('waitTimeSeconds')!, 10)\n\t\t\t\t: undefined,\n\t\t};\n\n\t\treturn new SNSSubscriber<TMessage>(connection, options);\n\t}\n\n\tasync subscribe(\n\t\tmessages: TMessage['type'][],\n\t\tlistener: (payload: TMessage) => Promise<void>,\n\t): Promise<void> {\n\t\t// Setup SQS queue and SNS subscription\n\t\tawait this.setupQueue();\n\t\tawait this.subscribeToTopic();\n\n\t\t// Create SQS connection for the subscriber\n\t\tconst sqsConnection = new SQSConnection({\n\t\t\tqueueUrl: this.queueUrl!,\n\t\t\tregion: (this.connection as any).config.region,\n\t\t\tendpoint: (this.connection as any).config.endpoint,\n\t\t\tcredentials: (this.connection as any).config.credentials,\n\t\t});\n\t\tawait sqsConnection.connect();\n\n\t\t// Use SQSSubscriber to receive messages, with topic filtering\n\t\tthis.sqsSubscriber = new SQSSubscriber<TMessage>(sqsConnection, {\n\t\t\twaitTimeSeconds: this.options.waitTimeSeconds,\n\t\t\tmaxMessages: this.options.maxMessages,\n\t\t\texpectedTopicArn: this.connection.topicArn,\n\t\t});\n\n\t\tawait this.sqsSubscriber.subscribe(messages, listener);\n\t}\n\n\t/**\n\t * Stop receiving messages and clean up resources\n\t */\n\tasync stop(): Promise<void> {\n\t\t// Stop SQS subscriber\n\t\tif (this.sqsSubscriber) {\n\t\t\tthis.sqsSubscriber.stop();\n\t\t}\n\n\t\t// Unsubscribe from topic\n\t\tif (this.subscriptionArn) {\n\t\t\ttry {\n\t\t\t\tconst command = new UnsubscribeCommand({\n\t\t\t\t\tSubscriptionArn: this.subscriptionArn,\n\t\t\t\t});\n\t\t\t\tawait this.connection.snsClient.send(command);\n\t\t\t} catch (_error) {}\n\t\t}\n\n\t\t// Delete queue if configured\n\t\tif (this.queueUrl && this.options.deleteQueueOnClose) {\n\t\t\ttry {\n\t\t\t\tconst command = new DeleteQueueCommand({\n\t\t\t\t\tQueueUrl: this.queueUrl,\n\t\t\t\t});\n\t\t\t\tawait this.sqsClient.send(command);\n\t\t\t} catch (_error) {}\n\t\t}\n\n\t\tthis.sqsClient.destroy();\n\t}\n\n\tprivate async setupQueue(): Promise<void> {\n\t\tif (this.options.createQueue) {\n\t\t\t// Create queue\n\t\t\tconst createCommand = new CreateQueueCommand({\n\t\t\t\tQueueName: this.options.queueName,\n\t\t\t});\n\t\t\tconst response = await this.sqsClient.send(createCommand);\n\t\t\tthis.queueUrl = response.QueueUrl!;\n\t\t} else {\n\t\t\tthrow new SnsQueueMissing(this.options.queueName);\n\t\t}\n\n\t\t// Get queue ARN\n\t\tconst attrsCommand = new GetQueueAttributesCommand({\n\t\t\tQueueUrl: this.queueUrl,\n\t\t\tAttributeNames: ['QueueArn'],\n\t\t});\n\t\tconst attrsResponse = await this.sqsClient.send(attrsCommand);\n\t\tthis.queueArn = attrsResponse.Attributes?.QueueArn!;\n\n\t\t// Set queue policy to allow SNS\n\t\tawait this.setQueuePolicy();\n\t}\n\n\tprivate async setQueuePolicy(): Promise<void> {\n\t\tconst policy = {\n\t\t\tVersion: '2012-10-17',\n\t\t\tStatement: [\n\t\t\t\t{\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tPrincipal: '*',\n\t\t\t\t\tAction: 'SQS:SendMessage',\n\t\t\t\t\tResource: this.queueArn,\n\t\t\t\t\tCondition: {\n\t\t\t\t\t\tArnEquals: {\n\t\t\t\t\t\t\t'aws:SourceArn': this.connection.topicArn,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\n\t\tconst command = new SetQueueAttributesCommand({\n\t\t\tQueueUrl: this.queueUrl,\n\t\t\tAttributes: {\n\t\t\t\tPolicy: JSON.stringify(policy),\n\t\t\t},\n\t\t});\n\n\t\tawait this.sqsClient.send(command);\n\t}\n\n\tprivate async subscribeToTopic(): Promise<void> {\n\t\tconst command = new SubscribeCommand({\n\t\t\tTopicArn: this.connection.topicArn,\n\t\t\tProtocol: 'sqs',\n\t\t\tEndpoint: this.queueArn,\n\t\t});\n\n\t\tconst response = await this.connection.snsClient.send(command);\n\t\tthis.subscriptionArn = response.SubscriptionArn!;\n\t}\n}\n\n/**\n * A subscriber asked to use a queue it may not create. The SQS queue behind an\n * SNS subscription has to exist first, or `createQueue` has to allow it.\n */\nexport class SnsQueueMissing extends Error {\n\tconstructor(readonly queueName: string | undefined) {\n\t\tsuper(\n\t\t\t`The SNS subscriber's queue${queueName ? ` \"${queueName}\"` : ''} is not created here: pass createQueue: true, or create the queue first.`,\n\t\t);\n\t\tthis.name = 'SnsQueueMissing';\n\t}\n}\n"],"mappings":";;;;;;;AAgBA,IAAa,gBAAb,MAAa,cAAyC;CACrD,OAAS;CACT;CACA,YAAoB;CACpB;CAEA,YAAY,QAA6B;EACxC,KAAK,SAAS;EAEd,MAAM,eAAgC;GACrC,QAAQ,OAAO;GACf,UAAU,OAAO;GACjB,aAAa,OAAO;EACrB;EAEA,KAAK,SAAS,IAAIA,oBAAAA,UAAU,YAAY;CACzC;;;;;CAMA,aAAa,qBACZ,kBACyB;EAIzB,MAAM,EAAE,UAAU,QAAQ,aAAA,mBAAA,MAA0B,gBAAgB;EACpE,MAAM,SAAS,IAAI,IAAI,gBAAgB,CAAC,CAAC;EAEzC,MAAM,SAA8B;GACnC;GACA;GACA;EACD;EAIA,MAAM,cAAc,OAAO,IAAI,aAAa;EAC5C,MAAM,kBAAkB,OAAO,IAAI,iBAAiB;EACpD,IAAI,eAAe,iBAClB,OAAO,cAAc;GACpB;GACA;GACA,cAAc,OAAO,IAAI,cAAc,KAAK,KAAA;EAC7C;EAGD,MAAM,aAAa,I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KAAK;IACf,WAAW,EACV,WAAW,EACV,iBAAiB,KAAK,WAAW,SAClC,EACD;GACD,CACD;EACD;EAEA,MAAM,UAAU,IAAIC,oBAAAA,0BAA0B;GAC7C,UAAU,KAAK;GACf,YAAY,EACX,QAAQ,KAAK,UAAU,MAAM,EAC9B;EACD,CAAC;EAED,MAAM,KAAK,UAAU,KAAK,OAAO;CAClC;CAEA,MAAc,mBAAkC;EAC/C,MAAM,UAAU,IAAIC,oBAAAA,iBAAiB;GACpC,UAAU,KAAK,WAAW;GAC1B,UAAU;GACV,UAAU,KAAK;EAChB,CAAC;EAED,MAAM,WAAW,MAAM,KAAK,WAAW,UAAU,KAAK,OAAO;EAC7D,KAAK,kBAAkB,SAAS;CACjC;AACD;;;;;AAMA,IAAa,kBAAb,cAAqC,MAAM;CACrB;CAArB,YAAY,WAAwC;EACnD,MACC,6BAA6B,YAAY,KAAK,UAAU,KAAK,GAAG,yEACjE;EAHoB,KAAA,YAAA;EAIpB,KAAK,OAAO;CACb;AACD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["SNSClient","publishTraced","PublishCommand","carrierAsAttributes","SQSClient","SQSConnection","SQSSubscriber","UnsubscribeCommand","DeleteQueueCommand","CreateQueueCommand","GetQueueAttributesCommand","SetQueueAttributesCommand","SubscribeCommand","parseUrl","SetSubscriptionAttributesCommand","GetSubscriptionAttributesCommand","UnsubscribeCommand","SubscribeCommand","SnsNotAConfirmation","ConfirmSubscriptionCommand","ListSubscriptionsByTopicCommand"],"sources":["../../src/sns/SNSConnection.ts","../../src/sns/SNSPublisher.ts","../../src/sns/SNSSubscriber.ts","../../src/sns/driver.ts","../../src/sns/push.ts"],"sourcesContent":["import { SNSClient, type SNSClientConfig } from '@aws-sdk/client-sns';\nimport type { EventConnection } from '../types';\nimport { EventPublisherType } from '../types';\nimport * as snsUrl from './snsUrl';\n\nexport interface SNSConnectionConfig {\n\ttopicArn: string;\n\tregion?: string;\n\tendpoint?: string; // Custom endpoint (e.g., for LocalStack)\n\t/**\n\t * Static keys, or a provider the SDK resolves them through — a deploy's\n\t * profile or chain, where nothing pins a key pair.\n\t */\n\tcredentials?: SNSClientConfig['credentials'];\n}\n\nexport class SNSConnection implements EventConnection {\n\treadonly type = EventPublisherType.SNS;\n\tprivate client: SNSClient;\n\tprivate connected = false;\n\tprivate config: SNSConnectionConfig;\n\n\tconstructor(config: SNSConnectionConfig) {\n\t\tthis.config = config;\n\n\t\tconst clientConfig: SNSClientConfig = {\n\t\t\tregion: config.region,\n\t\t\tendpoint: config.endpoint,\n\t\t\tcredentials: config.credentials,\n\t\t};\n\n\t\tthis.client = new SNSClient(clientConfig);\n\t}\n\n\t/**\n\t * Create an SNSConnection from a connection string\n\t * Format: sns://?topicArn=arn:aws:sns:region:account:topic®ion=us-east-1&endpoint=http://localhost:4566\n\t */\n\tstatic async fromConnectionString(\n\t\tconnectionString: string,\n\t): Promise<SNSConnection> {\n\t\t// Through the codec, not a second hand-rolled parse: the deploy target\n\t\t// composes these with `snsUrl.build`, and a string it cannot read back is\n\t\t// exactly the drift one shared module rules out.\n\t\tconst { topicArn, region, endpoint } = snsUrl.parse(connectionString);\n\t\tconst params = new URL(connectionString).searchParams;\n\n\t\tconst config: SNSConnectionConfig = {\n\t\t\ttopicArn,\n\t\t\tregion,\n\t\t\tendpoint,\n\t\t};\n\n\t\t// Credentials are not part of the address — see `snsUrl` — but a caller\n\t\t// may still pin them here, so they are read beside it rather than in it.\n\t\tconst accessKeyId = params.get('accessKeyId');\n\t\tconst secretAccessKey = params.get('secretAccessKey');\n\t\tif (accessKeyId && secretAccessKey) {\n\t\t\tconfig.credentials = {\n\t\t\t\taccessKeyId,\n\t\t\t\tsecretAccessKey,\n\t\t\t\tsessionToken: params.get('sessionToken') || undefined,\n\t\t\t};\n\t\t}\n\n\t\tconst connection = new SNSConnection(config);\n\t\tawait connection.connect();\n\t\treturn connection;\n\t}\n\n\tasync connect(): Promise<void> {\n\t\t// SNS doesn't have a traditional connection, but we mark as connected\n\t\tthis.connected = true;\n\t}\n\n\tasync close(): Promise<void> {\n\t\tthis.client.destroy();\n\t\tthis.connected = false;\n\t}\n\n\tisConnected(): boolean {\n\t\treturn this.connected;\n\t}\n\n\t/**\n\t * Get the underlying SNS client\n\t */\n\tget snsClient(): SNSClient {\n\t\treturn this.client;\n\t}\n\n\t/**\n\t * Get the topic ARN for this connection\n\t */\n\tget topicArn(): string {\n\t\treturn this.config.topicArn;\n\t}\n}\n","import { PublishCommand } from '@aws-sdk/client-sns';\nimport { carrierAsAttributes, publishTraced } from '../telemetry';\nimport type { EventPublisher, PublishableMessage } from '../types';\nimport type { SNSConnection } from './SNSConnection';\n\nexport type SNSPublisherOptions = {};\n\nexport class SNSPublisher<TMessage extends PublishableMessage<string, any>>\n\timplements EventPublisher<TMessage>\n{\n\tconstructor(\n\t\tprivate connection: SNSConnection,\n\t\t_options: SNSPublisherOptions = {},\n\t) {}\n\n\t/**\n\t * Create an SNSPublisher from a connection string\n\t * Format: sns://?topicArn=arn:aws:sns:region:account:topic®ion=us-east-1&endpoint=http://localhost:4566\n\t */\n\tstatic async fromConnectionString<\n\t\tTMessage extends PublishableMessage<string, any>,\n\t>(connectionString: string): Promise<SNSPublisher<TMessage>> {\n\t\tconst { SNSConnection } = await import('./SNSConnection');\n\t\tconst connection =\n\t\t\tawait SNSConnection.fromConnectionString(connectionString);\n\n\t\treturn new SNSPublisher<TMessage>(connection);\n\t}\n\n\tasync publish(messages: TMessage[]): Promise<void> {\n\t\tif (messages.length === 0) return;\n\n\t\tif (!this.connection.isConnected()) {\n\t\t\tawait this.connection.connect();\n\t\t}\n\n\t\tconst topicArn = this.connection.topicArn;\n\t\tconst destination = topicArn.split(':').pop() ?? topicArn;\n\t\tawait publishTraced(\n\t\t\tmessages,\n\t\t\t(message) => ({ system: 'aws_sns', destination, type: message.type }),\n\t\t\t(carriers) =>\n\t\t\t\tPromise.all(\n\t\t\t\t\tmessages.map((message, i) =>\n\t\t\t\t\t\tthis.publishMessage(message, carriers[i]),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t);\n\t}\n\n\tprivate async publishMessage(\n\t\tmessage: TMessage,\n\t\tcarrier: Record<string, string> | undefined,\n\t): Promise<void> {\n\t\tconst command = new PublishCommand({\n\t\t\tTopicArn: this.connection.topicArn,\n\t\t\tMessage: JSON.stringify({\n\t\t\t\ttype: message.type,\n\t\t\t\tpayload: message.payload,\n\t\t\t}),\n\t\t\tMessageAttributes: {\n\t\t\t\ttype: {\n\t\t\t\t\tDataType: 'String',\n\t\t\t\t\tStringValue: message.type,\n\t\t\t\t},\n\t\t\t\t// The trace context as message attributes: SNS hands them on to\n\t\t\t\t// an SQS subscription's envelope, an HTTP push and a Lambda record.\n\t\t\t\t...carrierAsAttributes(carrier),\n\t\t\t},\n\t\t});\n\n\t\tawait this.connection.snsClient.send(command);\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// Publisher doesn't own the connection\n\t\t// Connection should be closed by whoever created it\n\t}\n}\n","import { SubscribeCommand, UnsubscribeCommand } from '@aws-sdk/client-sns';\nimport {\n\tCreateQueueCommand,\n\tDeleteQueueCommand,\n\tGetQueueAttributesCommand,\n\tSetQueueAttributesCommand,\n\tSQSClient,\n} from '@aws-sdk/client-sqs';\nimport { SQSConnection } from '../sqs/SQSConnection';\nimport { SQSSubscriber } from '../sqs/SQSSubscriber';\nimport type { EventSubscriber, PublishableMessage } from '../types';\nimport type { SNSConnection } from './SNSConnection';\n\nexport interface SNSSubscriberOptions {\n\tqueueName?: string; // Optional queue name (defaults to auto-generated)\n\tcreateQueue?: boolean; // Auto-create SQS queue (default: true)\n\tdeleteQueueOnClose?: boolean; // Delete queue when subscriber closes (default: false for named queues, true for auto-generated)\n\twaitTimeSeconds?: number; // SQS long polling (default: 20)\n\tmaxMessages?: number; // Max messages per poll (default: 10)\n}\n\n/**\n * SNS Subscriber - receives push-based messages from SNS via SQS queue\n *\n * Architecture:\n * SNS Topic → (push) → SQS Queue → Subscriber\n *\n * This subscriber automatically:\n * 1. Creates an SQS queue (or uses existing one)\n * 2. Subscribes the queue to the SNS topic\n * 3. Receives messages pushed from SNS to the queue\n * 4. Filters messages by topic ARN and message type\n * 5. Processes and acknowledges messages\n *\n * Note: While SQS long-polling is used internally to receive messages,\n * this is an implementation detail of the SNS push delivery mechanism.\n * Messages are pushed from SNS to SQS, and we receive those pushed messages.\n */\nexport class SNSSubscriber<TMessage extends PublishableMessage<string, any>>\n\timplements EventSubscriber<TMessage>\n{\n\tprivate sqsClient: SQSClient;\n\tprivate queueUrl?: string;\n\tprivate queueArn?: string;\n\tprivate subscriptionArn?: string;\n\tprivate sqsSubscriber?: SQSSubscriber<TMessage>;\n\tprivate options: Required<SNSSubscriberOptions>;\n\n\tconstructor(\n\t\tprivate connection: SNSConnection,\n\t\toptions: SNSSubscriberOptions = {},\n\t) {\n\t\tthis.options = {\n\t\t\tqueueName:\n\t\t\t\toptions.queueName ||\n\t\t\t\t`sns-sub-${Date.now()}-${Math.random().toString(36).substring(7)}`,\n\t\t\tcreateQueue: options.createQueue ?? true,\n\t\t\tdeleteQueueOnClose: options.deleteQueueOnClose ?? !options.queueName, // Delete auto-generated queues\n\t\t\twaitTimeSeconds: options.waitTimeSeconds ?? 20,\n\t\t\tmaxMessages: options.maxMessages ?? 10,\n\t\t};\n\n\t\t// Create SQS client with same config as SNS\n\t\tthis.sqsClient = new SQSClient({\n\t\t\tregion: (this.connection as any).config.region,\n\t\t\tendpoint: (this.connection as any).config.endpoint,\n\t\t\tcredentials: (this.connection as any).config.credentials,\n\t\t});\n\t}\n\n\t/**\n\t * Create an SNSSubscriber from a connection string\n\t * Format: sns://?topicArn=...&queueName=myqueue®ion=us-east-1\n\t */\n\tstatic async fromConnectionString<\n\t\tTMessage extends PublishableMessage<string, any>,\n\t>(connectionString: string): Promise<SNSSubscriber<TMessage>> {\n\t\tconst url = new URL(connectionString);\n\t\tconst params = url.searchParams;\n\n\t\tconst { SNSConnection } = await import('./SNSConnection');\n\t\tconst connection =\n\t\t\tawait SNSConnection.fromConnectionString(connectionString);\n\n\t\tconst options: SNSSubscriberOptions = {\n\t\t\tqueueName: params.get('queueName') || undefined,\n\t\t\tcreateQueue: params.get('createQueue') !== 'false',\n\t\t\tdeleteQueueOnClose: params.get('deleteQueueOnClose') === 'true',\n\t\t\twaitTimeSeconds: params.get('waitTimeSeconds')\n\t\t\t\t? Number.parseInt(params.get('waitTimeSeconds')!, 10)\n\t\t\t\t: undefined,\n\t\t};\n\n\t\treturn new SNSSubscriber<TMessage>(connection, options);\n\t}\n\n\tasync subscribe(\n\t\tmessages: TMessage['type'][],\n\t\tlistener: (payload: TMessage) => Promise<void>,\n\t): Promise<void> {\n\t\t// Setup SQS queue and SNS subscription\n\t\tawait this.setupQueue();\n\t\tawait this.subscribeToTopic();\n\n\t\t// Create SQS connection for the subscriber\n\t\tconst sqsConnection = new SQSConnection({\n\t\t\tqueueUrl: this.queueUrl!,\n\t\t\tregion: (this.connection as any).config.region,\n\t\t\tendpoint: (this.connection as any).config.endpoint,\n\t\t\tcredentials: (this.connection as any).config.credentials,\n\t\t});\n\t\tawait sqsConnection.connect();\n\n\t\t// Use SQSSubscriber to receive messages, with topic filtering\n\t\tthis.sqsSubscriber = new SQSSubscriber<TMessage>(sqsConnection, {\n\t\t\twaitTimeSeconds: this.options.waitTimeSeconds,\n\t\t\tmaxMessages: this.options.maxMessages,\n\t\t\texpectedTopicArn: this.connection.topicArn,\n\t\t});\n\n\t\tawait this.sqsSubscriber.subscribe(messages, listener);\n\t}\n\n\t/**\n\t * Stop receiving messages and clean up resources\n\t */\n\tasync stop(): Promise<void> {\n\t\t// Stop SQS subscriber\n\t\tif (this.sqsSubscriber) {\n\t\t\tthis.sqsSubscriber.stop();\n\t\t}\n\n\t\t// Unsubscribe from topic\n\t\tif (this.subscriptionArn) {\n\t\t\ttry {\n\t\t\t\tconst command = new UnsubscribeCommand({\n\t\t\t\t\tSubscriptionArn: this.subscriptionArn,\n\t\t\t\t});\n\t\t\t\tawait this.connection.snsClient.send(command);\n\t\t\t} catch (_error) {}\n\t\t}\n\n\t\t// Delete queue if configured\n\t\tif (this.queueUrl && this.options.deleteQueueOnClose) {\n\t\t\ttry {\n\t\t\t\tconst command = new DeleteQueueCommand({\n\t\t\t\t\tQueueUrl: this.queueUrl,\n\t\t\t\t});\n\t\t\t\tawait this.sqsClient.send(command);\n\t\t\t} catch (_error) {}\n\t\t}\n\n\t\tthis.sqsClient.destroy();\n\t}\n\n\tprivate async setupQueue(): Promise<void> {\n\t\tif (this.options.createQueue) {\n\t\t\t// Create queue\n\t\t\tconst createCommand = new CreateQueueCommand({\n\t\t\t\tQueueName: this.options.queueName,\n\t\t\t});\n\t\t\tconst response = await this.sqsClient.send(createCommand);\n\t\t\tthis.queueUrl = response.QueueUrl!;\n\t\t} else {\n\t\t\tthrow new SnsQueueMissing(this.options.queueName);\n\t\t}\n\n\t\t// Get queue ARN\n\t\tconst attrsCommand = new GetQueueAttributesCommand({\n\t\t\tQueueUrl: this.queueUrl,\n\t\t\tAttributeNames: ['QueueArn'],\n\t\t});\n\t\tconst attrsResponse = await this.sqsClient.send(attrsCommand);\n\t\tthis.queueArn = attrsResponse.Attributes?.QueueArn!;\n\n\t\t// Set queue policy to allow SNS\n\t\tawait this.setQueuePolicy();\n\t}\n\n\tprivate async setQueuePolicy(): Promise<void> {\n\t\tconst policy = {\n\t\t\tVersion: '2012-10-17',\n\t\t\tStatement: [\n\t\t\t\t{\n\t\t\t\t\tEffect: 'Allow',\n\t\t\t\t\tPrincipal: '*',\n\t\t\t\t\tAction: 'SQS:SendMessage',\n\t\t\t\t\tResource: this.queueArn,\n\t\t\t\t\tCondition: {\n\t\t\t\t\t\tArnEquals: {\n\t\t\t\t\t\t\t'aws:SourceArn': this.connection.topicArn,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\n\t\tconst command = new SetQueueAttributesCommand({\n\t\t\tQueueUrl: this.queueUrl,\n\t\t\tAttributes: {\n\t\t\t\tPolicy: JSON.stringify(policy),\n\t\t\t},\n\t\t});\n\n\t\tawait this.sqsClient.send(command);\n\t}\n\n\tprivate async subscribeToTopic(): Promise<void> {\n\t\tconst command = new SubscribeCommand({\n\t\t\tTopicArn: this.connection.topicArn,\n\t\t\tProtocol: 'sqs',\n\t\t\tEndpoint: this.queueArn,\n\t\t});\n\n\t\tconst response = await this.connection.snsClient.send(command);\n\t\tthis.subscriptionArn = response.SubscriptionArn!;\n\t}\n}\n\n/**\n * A subscriber asked to use a queue it may not create. The SQS queue behind an\n * SNS subscription has to exist first, or `createQueue` has to allow it.\n */\nexport class SnsQueueMissing extends Error {\n\tconstructor(readonly queueName: string | undefined) {\n\t\tsuper(\n\t\t\t`The SNS subscriber's queue${queueName ? ` \"${queueName}\"` : ''} is not created here: pass createQueue: true, or create the queue first.`,\n\t\t);\n\t\tthis.name = 'SnsQueueMissing';\n\t}\n}\n","import type { EventsDriver } from '../registry';\nimport { EventPublisherType } from '../types';\nimport { SNSConnection } from './SNSConnection';\nimport { SNSPublisher } from './SNSPublisher';\nimport { SNSSubscriber } from './SNSSubscriber';\n\n/**\n * `sns://` — an SNS topic, consumed through an SQS queue subscribed to it.\n * Register it with `registerEventsDriver(snsEventsDriver)`; an AWS entry\n * registers `sqsEventsDriver` beside it.\n */\nexport const snsEventsDriver: EventsDriver = {\n\tscheme: EventPublisherType.SNS,\n\tconnect: (url) => SNSConnection.fromConnectionString(url),\n\tpublisher: (url) => SNSPublisher.fromConnectionString(url),\n\tpublisherFor: (connection) => new SNSPublisher(connection as SNSConnection),\n\tsubscriber: (url) => SNSSubscriber.fromConnectionString(url),\n\tsubscriberFor: (connection) => new SNSSubscriber(connection as SNSConnection),\n};\n","import {\n\tConfirmSubscriptionCommand,\n\tGetSubscriptionAttributesCommand,\n\tListSubscriptionsByTopicCommand,\n\tSetSubscriptionAttributesCommand,\n\tSubscribeCommand,\n\ttype SubscribeCommandInput,\n\tUnsubscribeCommand,\n} from '@aws-sdk/client-sns';\nimport { parseUrl, type SnsHttpMessage, SnsNotAConfirmation } from './message';\nimport type { SNSConnection } from './SNSConnection';\n\n/**\n * Subscribing an HTTP(S) endpoint to a topic, which takes the SNS API and so\n * the AWS SDK. Receiving what SNS then pushes takes neither: that is\n * `./message`, the `@geekmidas/events/sns/message` entry.\n */\n\n/** Where a subscription's filter policy is matched. */\nexport type SnsFilterPolicyScope = 'MessageAttributes' | 'MessageBody';\n\n/** What an HTTP subscription is created or brought up to date with. */\nexport interface HttpSubscriptionFilter {\n\t/**\n\t * The event types this endpoint takes. Becomes the subscription's filter\n\t * policy on the `type` attribute `SNSPublisher` sets, so SNS sends nothing\n\t * else — fan-out to every subscriber, each seeing only what it named.\n\t *\n\t * Absent, with no {@link filterPolicy} either, for a topic whose\n\t * publisher sets no `type` — a bucket's — whose subscriber filters what it\n\t * is sent.\n\t *\n\t * Ignored when {@link filterPolicy} is given.\n\t */\n\tevents?: readonly string[];\n\t/**\n\t * A filter policy of the caller's own, for messages SNS did not receive\n\t * from `SNSPublisher` — a bucket's notifications carry no `type` attribute,\n\t * so they are matched on their body instead.\n\t */\n\tfilterPolicy?: Record<string, unknown>;\n\t/** Where {@link filterPolicy} is matched. `MessageAttributes` by default. */\n\tfilterPolicyScope?: SnsFilterPolicyScope;\n\t/**\n\t * An SQS queue's ARN for what SNS gives up delivering. SNS retries an HTTP\n\t * endpoint for a limited time and then drops the message, so without one an\n\t * outage longer than that loses events.\n\t */\n\tdeadLetterQueueArn?: string;\n}\n\nexport interface SubscribeHttpEndpointOptions extends HttpSubscriptionFilter {\n\t/** The URL SNS POSTs to — `http:` or `https:`, which picks the protocol. */\n\tendpoint: string;\n}\n\n/** The subscription attributes a filter asks for, as SNS spells them. */\nfunction subscriptionAttributes(\n\tfilter: HttpSubscriptionFilter,\n): Record<string, string> {\n\tconst attributes: Record<string, string> = filter.filterPolicy\n\t\t? {\n\t\t\t\tFilterPolicyScope: filter.filterPolicyScope ?? 'MessageAttributes',\n\t\t\t\tFilterPolicy: JSON.stringify(filter.filterPolicy),\n\t\t\t}\n\t\t: filter.events\n\t\t\t? {\n\t\t\t\t\tFilterPolicyScope: 'MessageAttributes',\n\t\t\t\t\tFilterPolicy: JSON.stringify({ type: [...filter.events] }),\n\t\t\t\t}\n\t\t\t: {};\n\tif (filter.deadLetterQueueArn) {\n\t\tattributes.RedrivePolicy = JSON.stringify({\n\t\t\tdeadLetterTargetArn: filter.deadLetterQueueArn,\n\t\t});\n\t}\n\treturn attributes;\n}\n\n/** The protocol SNS delivers to an endpoint with, from its URL. */\nfunction protocolOf(endpoint: string): 'http' | 'https' {\n\tconst protocol = parseUrl(endpoint)?.protocol.replace(':', '');\n\tif (protocol !== 'http' && protocol !== 'https') {\n\t\tthrow new SnsEndpointNotHttp(endpoint);\n\t}\n\treturn protocol;\n}\n\n/** Bring an existing subscription's attributes up to what is asked for. */\nasync function updateAttributes(\n\tconnection: SNSConnection,\n\tsubscriptionArn: string,\n\tcurrent: Record<string, string>,\n\twanted: Record<string, string>,\n): Promise<void> {\n\tfor (const [name, value] of Object.entries(wanted)) {\n\t\tif (current[name] === value) continue;\n\t\tawait connection.snsClient.send(\n\t\t\tnew SetSubscriptionAttributesCommand({\n\t\t\t\tSubscriptionArn: subscriptionArn,\n\t\t\t\tAttributeName: name,\n\t\t\t\tAttributeValue: value,\n\t\t\t}),\n\t\t);\n\t}\n}\n\n/**\n * Subscribe an HTTP endpoint to the connection's topic, converging on one\n * confirmed subscription with the filter asked for — so it is safe on every\n * start. What a server does against an emulator, where nothing deploys it;\n * against SNS itself the deploy owns the subscription\n * ({@link reconcileHttpSubscriptions}).\n *\n * - **none yet** — subscribed; SNS sends a confirmation to the endpoint.\n * - **confirmed** — its filter and dead-letter queue are brought up to date.\n * Subscribing again with different attributes is an error on SNS, and the\n * events a subscriber names change.\n * - **stuck pending** — a confirmation that never landed (the endpoint was\n * down, or answered wrong). Subscribing the same endpoint again is a no-op\n * on an emulator, so it is dropped and subscribed afresh, which sends a new\n * confirmation.\n */\nexport async function subscribeHttpEndpoint(\n\tconnection: SNSConnection,\n\toptions: SubscribeHttpEndpointOptions,\n): Promise<string | undefined> {\n\tconst protocol = protocolOf(options.endpoint);\n\tconst attributes = subscriptionAttributes(options);\n\n\tconst client = connection.snsClient;\n\tconst existing = (await topicSubscriptions(connection)).find(\n\t\t(s) => s.endpoint === options.endpoint,\n\t)?.arn;\n\tif (existing) {\n\t\tconst { Attributes = {} } = await client.send(\n\t\t\tnew GetSubscriptionAttributesCommand({ SubscriptionArn: existing }),\n\t\t);\n\t\tif (Attributes.PendingConfirmation === 'true') {\n\t\t\tawait client.send(new UnsubscribeCommand({ SubscriptionArn: existing }));\n\t\t} else {\n\t\t\tawait updateAttributes(connection, existing, Attributes, attributes);\n\t\t\treturn existing;\n\t\t}\n\t}\n\n\tconst { SubscriptionArn } = await client.send(\n\t\tnew SubscribeCommand({\n\t\t\tTopicArn: connection.topicArn,\n\t\t\tProtocol: protocol,\n\t\t\tEndpoint: options.endpoint,\n\t\t\tAttributes: attributes as SubscribeCommandInput['Attributes'],\n\t\t\tReturnSubscriptionArn: true,\n\t\t}),\n\t);\n\treturn SubscriptionArn;\n}\n\n/** One endpoint the deploy wants subscribed, under the name it is recorded by. */\nexport interface HttpSubscriptionSpec extends HttpSubscriptionFilter {\n\t/** What the ARN is recorded under — the subscriber's export. */\n\tname: string;\n\t/** The URL SNS POSTs to. */\n\tendpoint: string;\n}\n\nexport interface ReconcileHttpSubscriptionsOptions {\n\t/** Every endpoint that should be subscribed to the topic. */\n\tendpoints: readonly HttpSubscriptionSpec[];\n\t/**\n\t * The host these endpoints answer on. A subscription to an endpoint on it\n\t * that is not in {@link endpoints} — a subscriber renamed or removed — is\n\t * unsubscribed; anything subscribed on another host is somebody else's and\n\t * left alone.\n\t */\n\townedHost: string;\n}\n\nexport interface ReconciledHttpSubscriptions {\n\t/** Each endpoint's subscription ARN, by its name — stable across runs. */\n\tsubscriptions: Record<string, string>;\n\t/** The names whose subscription SNS still waits to have confirmed. */\n\tpending: string[];\n\t/** The ARNs of what was unsubscribed as no longer wanted. */\n\tremoved: string[];\n}\n\n/**\n * Converge a topic's HTTP subscriptions on the endpoints a deploy wants, and\n * answer each one's ARN for the deploy to record and hand to the server.\n *\n * The deploy's half of push delivery against SNS itself: the server never\n * subscribes, so its credentials need no `sns:Subscribe` — and the only\n * subscriptions to the topic are ones the deploy made.\n *\n * Run it twice: once before the server starts, for the ARNs it is configured\n * with — SNS answers one even while the subscription waits to be confirmed —\n * and once the server is up, which subscribes each still-pending endpoint\n * again so SNS resends its confirmation to a server now there to answer it.\n * The ARN does not change between the two.\n *\n * - **absent** — subscribed with its filter.\n * - **present** — its filter and dead-letter queue are brought up to date;\n * pending, it is subscribed again to resend the confirmation.\n * - **stale** — on {@link ReconcileHttpSubscriptionsOptions.ownedHost} and no\n * longer wanted: unsubscribed. (A stale one SNS still lists as pending has\n * no ARN to act on; SNS drops it unconfirmed after three days.)\n */\nexport async function reconcileHttpSubscriptions(\n\tconnection: SNSConnection,\n\toptions: ReconcileHttpSubscriptionsOptions,\n): Promise<ReconciledHttpSubscriptions> {\n\tconst client = connection.snsClient;\n\tconst listed = await topicSubscriptions(connection);\n\tconst result: ReconciledHttpSubscriptions = {\n\t\tsubscriptions: {},\n\t\tpending: [],\n\t\tremoved: [],\n\t};\n\n\tfor (const spec of options.endpoints) {\n\t\tconst protocol = protocolOf(spec.endpoint);\n\t\tconst attributes = subscriptionAttributes(spec);\n\t\tconst subscribe = async () =>\n\t\t\t(\n\t\t\t\tawait client.send(\n\t\t\t\t\tnew SubscribeCommand({\n\t\t\t\t\t\tTopicArn: connection.topicArn,\n\t\t\t\t\t\tProtocol: protocol,\n\t\t\t\t\t\tEndpoint: spec.endpoint,\n\t\t\t\t\t\tAttributes: attributes as SubscribeCommandInput['Attributes'],\n\t\t\t\t\t\tReturnSubscriptionArn: true,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t).SubscriptionArn;\n\n\t\tconst existing = listed.find((s) => s.endpoint === spec.endpoint)?.arn;\n\t\tlet arn: string | undefined;\n\t\tlet pending: boolean;\n\t\tif (existing) {\n\t\t\tconst { Attributes = {} } = await client.send(\n\t\t\t\tnew GetSubscriptionAttributesCommand({ SubscriptionArn: existing }),\n\t\t\t);\n\t\t\tawait updateAttributes(connection, existing, Attributes, attributes);\n\t\t\tpending = Attributes.PendingConfirmation === 'true';\n\t\t\t// Subscribing a pending endpoint again resends its confirmation,\n\t\t\t// under the same ARN.\n\t\t\tarn = pending ? ((await subscribe()) ?? existing) : existing;\n\t\t} else {\n\t\t\t// Absent — or pending on SNS itself, which lists it with no ARN:\n\t\t\t// subscribing answers the one it has, and resends the confirmation.\n\t\t\tarn = await subscribe();\n\t\t\tpending = true;\n\t\t}\n\t\tif (!arn) {\n\t\t\tthrow new SnsSubscriptionArnMissing(connection.topicArn, spec.endpoint);\n\t\t}\n\n\t\tresult.subscriptions[spec.name] = arn;\n\t\tif (pending) result.pending.push(spec.name);\n\t}\n\n\tconst wanted = new Set(options.endpoints.map((spec) => spec.endpoint));\n\tfor (const { arn, endpoint } of listed) {\n\t\tif (!arn || wanted.has(endpoint)) continue;\n\t\tif (parseUrl(endpoint)?.host !== options.ownedHost) continue;\n\t\tawait client.send(new UnsubscribeCommand({ SubscriptionArn: arn }));\n\t\tresult.removed.push(arn);\n\t}\n\n\treturn result;\n}\n\n/**\n * Confirm a subscription through the API, as its topic's owner, rather than by\n * visiting the URL SNS sent.\n *\n * `AuthenticateOnUnsubscribe` is the point of it. A subscription confirmed by\n * visiting `SubscribeURL` can be removed by anyone holding the\n * `UnsubscribeURL` every notification carries — one unauthenticated GET, and\n * the endpoint is silently cut off. Confirmed this way, only the topic's owner\n * can unsubscribe it. All it takes of the caller's credentials is\n * `sns:ConfirmSubscription` on this one topic.\n */\nexport async function confirmSubscription(\n\tconnection: SNSConnection,\n\tmessage: SnsHttpMessage,\n): Promise<string | undefined> {\n\tif (message.Type !== 'SubscriptionConfirmation' || !message.Token) {\n\t\tthrow new SnsNotAConfirmation(message.Type);\n\t}\n\n\tconst { SubscriptionArn } = await connection.snsClient.send(\n\t\tnew ConfirmSubscriptionCommand({\n\t\t\tTopicArn: message.TopicArn,\n\t\t\tToken: message.Token,\n\t\t\tAuthenticateOnUnsubscribe: 'true',\n\t\t}),\n\t);\n\treturn SubscriptionArn;\n}\n\n/**\n * Every subscription on the connection's topic, with the ARN SNS names for it\n * — none for one real SNS lists as `PendingConfirmation`, which there is no\n * ARN to act on (and which a new Subscribe resends the confirmation of anyway).\n */\nasync function topicSubscriptions(\n\tconnection: SNSConnection,\n): Promise<{ arn?: string; endpoint: string }[]> {\n\tconst found: { arn?: string; endpoint: string }[] = [];\n\tlet NextToken: string | undefined;\n\tdo {\n\t\tconst page = await connection.snsClient.send(\n\t\t\tnew ListSubscriptionsByTopicCommand({\n\t\t\t\tTopicArn: connection.topicArn,\n\t\t\t\tNextToken,\n\t\t\t}),\n\t\t);\n\t\tfor (const s of page.Subscriptions ?? []) {\n\t\t\tif (!s.Endpoint) continue;\n\t\t\tfound.push({\n\t\t\t\tendpoint: s.Endpoint,\n\t\t\t\t...(s.SubscriptionArn?.startsWith('arn:')\n\t\t\t\t\t? { arn: s.SubscriptionArn }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t}\n\t\tNextToken = page.NextToken;\n\t} while (NextToken);\n\treturn found;\n}\n\nexport class SnsEndpointNotHttp extends Error {\n\tconstructor(readonly endpoint: string) {\n\t\tsuper(\n\t\t\t`'${endpoint}' is not an http(s) URL. SNS pushes to an HTTP endpoint; ` +\n\t\t\t\t'subscribe a queue for anything else.',\n\t\t);\n\t\tthis.name = 'SnsEndpointNotHttp';\n\t}\n}\n\nexport class SnsSubscriptionArnMissing extends Error {\n\tconstructor(\n\t\treadonly topicArn: string,\n\t\treadonly endpoint: string,\n\t) {\n\t\tsuper(\n\t\t\t`Subscribing '${endpoint}' to '${topicArn}' answered no subscription ` +\n\t\t\t\t'ARN, so there is nothing to record for the server to acc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