statocysts 0.0.5 → 0.1.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.
@@ -0,0 +1,9 @@
1
+ import { a as DEFAULT_EXTRACTOR, c as ServiceProvider, i as slackProvider, l as defineProvider, n as SlackData, o as DefineProviderContext, r as SlackOptions, s as DefineProviderOptions, t as jsonProvider } from "./index-pwxPZaBo.js";
2
+ import { FetchOptions } from "ofetch";
3
+
4
+ //#region src/browser.d.ts
5
+ type Protocol = 'json:' | 'slack:';
6
+ declare const SUPPORTED_PROTOCOLS: readonly ["json:", "slack:"];
7
+ declare function send(url: string | URL, message: string, options?: FetchOptions): Promise<void>;
8
+ //#endregion
9
+ export { DEFAULT_EXTRACTOR, DefineProviderContext, DefineProviderOptions, Protocol, SUPPORTED_PROTOCOLS, ServiceProvider, SlackData, SlackOptions, defineProvider, jsonProvider, send, slackProvider };
@@ -0,0 +1,19 @@
1
+ import { a as assert, i as defineProvider, n as slackProvider, r as DEFAULT_EXTRACTOR, t as jsonProvider } from "./shared-DLVVDcdQ.js";
2
+ import { ofetch } from "ofetch";
3
+
4
+ //#region src/browser.ts
5
+ const SUPPORTED_PROTOCOLS = ["json:", "slack:"];
6
+ const providers = {
7
+ "json:": jsonProvider,
8
+ "slack:": slackProvider
9
+ };
10
+ async function send(url, message, options) {
11
+ const _url = typeof url === "string" ? new URL(url) : url;
12
+ assert(SUPPORTED_PROTOCOLS.includes(_url.protocol), `Unsupported protocol ${_url.protocol}`);
13
+ const provider = providers[_url.protocol];
14
+ if (!provider) throw new Error(`Unsupported protocol ${_url.protocol}`);
15
+ await ofetch(await provider.buildRequest(_url.toString(), message), options);
16
+ }
17
+
18
+ //#endregion
19
+ export { DEFAULT_EXTRACTOR, SUPPORTED_PROTOCOLS, defineProvider, jsonProvider, send, slackProvider };
@@ -0,0 +1,50 @@
1
+ //#region src/core/provider.d.ts
2
+ interface ServiceProvider<Protocol extends string, Data = unknown, Options = unknown> {
3
+ readonly protocol: Protocol;
4
+ $infer: Data;
5
+ defaultOptions: Options | undefined;
6
+ buildRequest: (url: string, message: string, options?: Options) => Promise<Request>;
7
+ }
8
+ interface DefineProviderContext<Data = unknown> {
9
+ url: URL;
10
+ message: string;
11
+ data: Data;
12
+ }
13
+ interface DefineProviderOptions<Data = unknown, Options = unknown> {
14
+ defaultOptions?: Options;
15
+ extractor?: (url: URL) => Data;
16
+ createRequest: (this: DefineProviderContext<Data>, ctx: DefineProviderContext<Data>, Options: Options) => Request;
17
+ }
18
+ declare const DEFAULT_EXTRACTOR: (url: URL) => unknown;
19
+ declare function defineProvider<const Protocol extends string, Data = unknown, Options = unknown>(protocol: Protocol, createOptions: DefineProviderOptions<Data, Options>): ServiceProvider<Protocol, Data, Options>;
20
+ //#endregion
21
+ //#region src/services/chat/slack/index.d.ts
22
+ interface SlackData {
23
+ type: 'bot' | 'webhook';
24
+ }
25
+ interface SlackOptions {
26
+ /**
27
+ * The base URL for webhook services
28
+ *
29
+ * @default `https://hooks.slack.com/services`
30
+ */
31
+ hookBaseUrl?: string;
32
+ /**
33
+ * The base URL for bot API services
34
+ *
35
+ * @default `https://slack.com/api`
36
+ */
37
+ botApiBaseUrl?: string;
38
+ /**
39
+ * The body of the request
40
+ *
41
+ * NOTICE*: This will override the body of the request. You should known what you are doing.
42
+ */
43
+ body?: Record<string, any>;
44
+ }
45
+ declare const slackProvider: ServiceProvider<"slack:", SlackData, SlackOptions>;
46
+ //#endregion
47
+ //#region src/services/specialized/json/index.d.ts
48
+ declare const jsonProvider: ServiceProvider<"json:", unknown, unknown>;
49
+ //#endregion
50
+ export { DEFAULT_EXTRACTOR as a, ServiceProvider as c, slackProvider as i, defineProvider as l, SlackData as n, DefineProviderContext as o, SlackOptions as r, DefineProviderOptions as s, jsonProvider as t };
package/dist/index.d.ts CHANGED
@@ -1,31 +1,9 @@
1
+ import { a as DEFAULT_EXTRACTOR, c as ServiceProvider, i as slackProvider, l as defineProvider, n as SlackData, o as DefineProviderContext, r as SlackOptions, s as DefineProviderOptions, t as jsonProvider } from "./index-pwxPZaBo.js";
1
2
  import { FetchOptions } from "ofetch";
2
- import { z } from "zod";
3
3
 
4
- //#region src/sender.d.ts
5
- type Protocol = 'generic:' | 'slack:';
6
- declare const SUPPORTED_PROTOCOLS: string[];
4
+ //#region src/index.d.ts
5
+ type Protocol = 'json:' | 'slack:';
6
+ declare const SUPPORTED_PROTOCOLS: readonly ["json:", "slack:"];
7
7
  declare function send(url: string | URL, message: string, options?: FetchOptions): Promise<void>;
8
8
  //#endregion
9
- //#region src/services/chat/slack.d.ts
10
- declare const slackOptionsSchema: z.ZodObject<{
11
- botname: z.ZodOptional<z.ZodString>;
12
- icon: z.ZodOptional<z.ZodString>;
13
- color: z.ZodOptional<z.ZodString>;
14
- title: z.ZodOptional<z.ZodString>;
15
- thread_ts: z.ZodOptional<z.ZodString>;
16
- }, z.core.$strip>;
17
- type SlackOptions = z.infer<typeof slackOptionsSchema>;
18
- declare function buildSlackRequest(url: URL, message: string): Request;
19
- //#endregion
20
- //#region src/services/specialized/generic.d.ts
21
- declare const genericOptionsSchema: z.ZodObject<{
22
- template: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
23
- json: "json";
24
- plaintext: "plaintext";
25
- }>>>;
26
- method: z.ZodDefault<z.ZodOptional<z.ZodString>>;
27
- }, z.core.$strip>;
28
- type GenericOptions = z.infer<typeof genericOptionsSchema>;
29
- declare function buildGenericRequest(url: URL, message: string): Request;
30
- //#endregion
31
- export { GenericOptions, Protocol, SUPPORTED_PROTOCOLS, SlackOptions, buildGenericRequest, buildSlackRequest, send };
9
+ export { DEFAULT_EXTRACTOR, DefineProviderContext, DefineProviderOptions, Protocol, SUPPORTED_PROTOCOLS, ServiceProvider, SlackData, SlackOptions, defineProvider, jsonProvider, send, slackProvider };
package/dist/index.js CHANGED
@@ -1,145 +1,19 @@
1
+ import { a as assert, i as defineProvider, n as slackProvider, r as DEFAULT_EXTRACTOR, t as jsonProvider } from "./shared-DLVVDcdQ.js";
1
2
  import { ofetch } from "ofetch";
2
- import { z } from "zod";
3
3
 
4
- //#region src/utils/assert.ts
5
- function assert(condition, message) {
6
- if (!condition) throw typeof message === "string" ? new Error(message) : message;
7
- }
8
-
9
- //#endregion
10
- //#region src/services/chat/slack.ts
11
- const slackOptionsSchema = z.object({
12
- botname: z.string().optional(),
13
- icon: z.string().optional(),
14
- color: z.string().optional(),
15
- title: z.string().optional(),
16
- thread_ts: z.string().optional()
17
- });
18
- function isBotApiFormat(url) {
19
- return url.username === "xoxb";
20
- }
21
- function isWebhookFormat(url) {
22
- return url.username === "hook";
23
- }
24
- function parseBotToken(url) {
25
- assert(url.password, "Bot token is required");
26
- return url.password;
27
- }
28
- function parseWebhookToken(url) {
29
- assert(url.password, "Webhook token is required");
30
- const parts = url.password.split("-");
31
- assert(parts.length === 3, "Invalid webhook token format");
32
- return {
33
- id: parts[0],
34
- token: parts[1],
35
- secret: parts[2]
36
- };
37
- }
38
- function buildBotApiRequest(url, message, options) {
39
- const token = parseBotToken(url);
40
- const body = {
41
- channel: url.hostname,
42
- text: message
43
- };
44
- if (options.botname) body.username = options.botname;
45
- if (options.icon) if (options.icon.startsWith(":") && options.icon.endsWith(":")) body.icon_emoji = options.icon;
46
- else body.icon_url = options.icon;
47
- if (options.thread_ts) body.thread_ts = options.thread_ts;
48
- const attachments = [];
49
- if (options.color || options.title) {
50
- const attachment = {};
51
- if (options.color) attachment.color = options.color.startsWith("%23") ? decodeURIComponent(options.color) : options.color;
52
- if (options.title) attachment.title = options.title;
53
- attachments.push(attachment);
54
- }
55
- if (attachments.length > 0) body.attachments = attachments;
56
- return new Request("https://slack.com/api/chat.postMessage", {
57
- method: "POST",
58
- headers: {
59
- "Authorization": `Bearer xoxb-${token}`,
60
- "Content-Type": "application/json"
61
- },
62
- body: JSON.stringify(body)
63
- });
64
- }
65
- function buildWebhookRequest(url, message, options) {
66
- const { id, token, secret } = parseWebhookToken(url);
67
- const body = { text: message };
68
- if (options.botname) body.username = options.botname;
69
- if (options.icon) if (options.icon.startsWith(":") && options.icon.endsWith(":")) body.icon_emoji = options.icon;
70
- else body.icon_url = options.icon;
71
- const attachments = [];
72
- if (options.color || options.title) {
73
- const attachment = {};
74
- if (options.color) attachment.color = options.color.startsWith("%23") ? decodeURIComponent(options.color) : options.color;
75
- if (options.title) attachment.title = options.title;
76
- attachments.push(attachment);
77
- }
78
- if (attachments.length > 0) body.attachments = attachments;
79
- return new Request(`https://hooks.slack.com/services/${id}/${token}/${secret}`, {
80
- method: "POST",
81
- headers: { "Content-Type": "application/json" },
82
- body: JSON.stringify(body)
83
- });
84
- }
85
- function buildSlackRequest(url, message) {
86
- assert(url.protocol === "slack:", `Unexpected protocol ${url.protocol}`);
87
- const params = new URLSearchParams(url.search);
88
- const options = slackOptionsSchema.parse(Object.fromEntries(params.entries()));
89
- if (isBotApiFormat(url)) return buildBotApiRequest(url, message, options);
90
- if (isWebhookFormat(url)) return buildWebhookRequest(url, message, options);
91
- throw new Error(`Unsupported Slack URL format: ${url.toString()}`);
92
- }
93
-
94
- //#endregion
95
- //#region src/services/specialized/generic.ts
96
- const genericOptionsSchema = z.object({
97
- template: z.enum(["json", "plaintext"]).optional().default("json"),
98
- method: z.string().optional().default("POST")
99
- });
100
- function isOptionParam(key) {
101
- return !key.startsWith("@") && !key.startsWith("$");
102
- }
103
- function buildGenericRequest(url, message) {
104
- assert(url.protocol === "generic:", `Unexpected protocol ${url.protocol}`);
105
- const params = new URLSearchParams(url.hash.slice(1));
106
- const allParamsEntries = Array.from(params.entries());
107
- const optionsParams = Object.fromEntries(allParamsEntries.filter(([key]) => isOptionParam(key)));
108
- const options = genericOptionsSchema.parse(optionsParams);
109
- const headers = Object.fromEntries(allParamsEntries.filter(([key]) => key.startsWith("@")).map(([key, value]) => [key.slice(1), value]));
110
- const dataProperties = Object.fromEntries(allParamsEntries.filter(([key]) => key.startsWith("$")).map(([key, value]) => [key.slice(1), value]));
111
- const targetUrl = new URL(url.host + url.pathname);
112
- return new Request(targetUrl.toString(), {
113
- method: options.method,
114
- headers: {
115
- "Content-Type": options.template === "json" ? "application/json" : "text/plain",
116
- ...headers
117
- },
118
- body: options.template === "json" ? JSON.stringify({
119
- ...dataProperties,
120
- message
121
- }) : message
122
- });
123
- }
124
-
125
- //#endregion
126
- //#region src/sender.ts
127
- const SUPPORTED_PROTOCOLS = ["generic:", "slack:"];
4
+ //#region src/index.ts
5
+ const SUPPORTED_PROTOCOLS = ["json:", "slack:"];
6
+ const providers = {
7
+ "json:": jsonProvider,
8
+ "slack:": slackProvider
9
+ };
128
10
  async function send(url, message, options) {
129
11
  const _url = typeof url === "string" ? new URL(url) : url;
130
12
  assert(SUPPORTED_PROTOCOLS.includes(_url.protocol), `Unsupported protocol ${_url.protocol}`);
131
- let req;
132
- switch (_url.protocol) {
133
- case "generic:":
134
- req = buildGenericRequest(_url, message);
135
- break;
136
- case "slack:":
137
- req = buildSlackRequest(_url, message);
138
- break;
139
- default: throw new Error(`Unsupported protocol ${_url.protocol}`);
140
- }
141
- await ofetch(req, options);
13
+ const provider = providers[_url.protocol];
14
+ if (!provider) throw new Error(`Unsupported protocol ${_url.protocol}`);
15
+ await ofetch(await provider.buildRequest(_url.toString(), message), options);
142
16
  }
143
17
 
144
18
  //#endregion
145
- export { SUPPORTED_PROTOCOLS, buildGenericRequest, buildSlackRequest, send };
19
+ export { DEFAULT_EXTRACTOR, SUPPORTED_PROTOCOLS, defineProvider, jsonProvider, send, slackProvider };
@@ -0,0 +1,107 @@
1
+ import defu from "defu";
2
+ import { withProtocol, withoutLeadingSlash } from "ufo";
3
+
4
+ //#region src/utils/assert.ts
5
+ function assert(condition, message) {
6
+ if (!condition) throw typeof message === "string" ? new Error(message) : message;
7
+ }
8
+
9
+ //#endregion
10
+ //#region src/core/provider.ts
11
+ const DEFAULT_EXTRACTOR = (url) => Object.fromEntries(url.searchParams.entries());
12
+ function defineProvider(protocol, createOptions) {
13
+ const createOpt = defu(createOptions, { extractor: DEFAULT_EXTRACTOR });
14
+ const buildRequest = async (protocolUrl, message, options) => {
15
+ const url = new URL(protocolUrl);
16
+ assert(url.protocol === protocol, `Unexpected protocol "${url.protocol}"`);
17
+ const ctx = {
18
+ data: createOpt.extractor(url),
19
+ url,
20
+ message
21
+ };
22
+ const opts = defu(createOptions.defaultOptions ?? {}, options ?? {});
23
+ return createOptions.createRequest.call(ctx, ctx, opts);
24
+ };
25
+ return {
26
+ get protocol() {
27
+ return protocol;
28
+ },
29
+ buildRequest,
30
+ get defaultOptions() {
31
+ return createOptions.defaultOptions;
32
+ },
33
+ $infer: {}
34
+ };
35
+ }
36
+
37
+ //#endregion
38
+ //#region src/services/chat/slack/index.ts
39
+ const slackProvider = defineProvider("slack:", {
40
+ extractor: (url) => {
41
+ assert(url.hostname === "bot" || url.hostname === "webhook", `Invalid slack URL: ${url.toString()}`);
42
+ if (url.hostname === "bot") {
43
+ assert(url.username, "Channel ID is required");
44
+ assert(url.password, "Bot token is required");
45
+ } else assert(url.pathname.split("/").filter(Boolean).length === 3, "Webhook URL is invalid");
46
+ return { type: url.hostname };
47
+ },
48
+ defaultOptions: {
49
+ hookBaseUrl: "https://hooks.slack.com/",
50
+ botApiBaseUrl: "https://slack.com/"
51
+ },
52
+ createRequest(_, options) {
53
+ const { type } = this.data;
54
+ let url;
55
+ const headers = new Headers([["Content-Type", "application/json"]]);
56
+ const body = { text: this.message };
57
+ if (type === "bot") {
58
+ const { username: channel, password: token, searchParams } = this.url;
59
+ url = new URL("/api/chat.postMessage", options.botApiBaseUrl);
60
+ searchParams.forEach((value, key) => {
61
+ url.searchParams.set(key, value);
62
+ });
63
+ headers.set("Authorization", `Bearer ${token}`);
64
+ body.channel = channel;
65
+ } else {
66
+ const { searchParams } = this.url;
67
+ url = new URL(`/services/${withoutLeadingSlash(this.url.pathname)}`, options.hookBaseUrl);
68
+ searchParams.forEach((value, key) => {
69
+ url.searchParams.set(key, value);
70
+ });
71
+ }
72
+ return new Request(url, {
73
+ method: "POST",
74
+ headers,
75
+ body: JSON.stringify(options.body ?? body)
76
+ });
77
+ }
78
+ });
79
+
80
+ //#endregion
81
+ //#region src/services/specialized/json/index.ts
82
+ const jsonProvider = defineProvider("json:", { createRequest() {
83
+ const url = new URL(this.url);
84
+ const headers = new Headers([["Content-Type", "application/json"]]);
85
+ const body = { message: this.message };
86
+ Array.from(url.searchParams.entries()).forEach(([key, value]) => {
87
+ if (key.startsWith(" ")) {
88
+ url.searchParams.delete(key);
89
+ const headerKey = key.slice(1);
90
+ if (headers.has(headerKey)) headers.set(headerKey, value);
91
+ else headers.append(headerKey, value);
92
+ } else if (key.startsWith(":")) {
93
+ url.searchParams.delete(key);
94
+ const propertyKey = key.slice(1);
95
+ body[propertyKey] = value;
96
+ }
97
+ });
98
+ const requestUrl = withProtocol(url.toString(), "https:");
99
+ return new Request(requestUrl, {
100
+ method: "POST",
101
+ body: JSON.stringify(body),
102
+ headers
103
+ });
104
+ } });
105
+
106
+ //#endregion
107
+ export { assert as a, defineProvider as i, slackProvider as n, DEFAULT_EXTRACTOR as r, jsonProvider as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "statocysts",
3
3
  "type": "module",
4
- "version": "0.0.5",
4
+ "version": "0.1.0",
5
5
  "description": "Notification library for JavaScript",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/octoplorer/statocysts",
@@ -17,12 +17,20 @@
17
17
  "shoutrrr"
18
18
  ],
19
19
  "exports": {
20
- ".": "./dist/index.js",
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ },
24
+ "./browser": {
25
+ "types": "./dist/browser.d.ts",
26
+ "import": "./dist/browser.js"
27
+ },
21
28
  "./package.json": "./package.json"
22
29
  },
23
30
  "main": "./dist/index.js",
24
31
  "module": "./dist/index.js",
25
32
  "types": "./dist/index.d.ts",
33
+ "browser": "./dist/browser.js",
26
34
  "files": [
27
35
  "dist"
28
36
  ],
@@ -33,12 +41,15 @@
33
41
  "node": ">=24.12.0"
34
42
  },
35
43
  "dependencies": {
44
+ "defu": "^6.1.4",
36
45
  "ofetch": "^1.5.1",
46
+ "ufo": "^1.6.1",
37
47
  "zod": "^4.2.1"
38
48
  },
39
49
  "devDependencies": {
40
50
  "@antfu/eslint-config": "^6.7.1",
41
51
  "@types/node": "^25.0.2",
52
+ "@vitest/coverage-v8": "4.0.15",
42
53
  "bumpp": "^10.3.2",
43
54
  "eslint": "^9.39.2",
44
55
  "eslint-plugin-format": "^1.1.0",