react-credly-badges 0.0.0-stage → 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.
package/README.md CHANGED
@@ -1,3 +1,132 @@
1
- # Temporary Holding Version
1
+ # react-credly-badges
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A lightweight React + TypeScript library for displaying public Credly badges
4
+ using a Credly username.
5
+
6
+ - Horizontal and vertical layouts.
7
+ - Badge images link to their Credly verification pages.
8
+ - Fetches badges through a hosted Cloudflare Worker; no application backend required.
9
+ - Supports React 17, 18.2, and 19.
10
+
11
+ ## Usage
12
+
13
+ ```sh
14
+ npm install react-credly-badges
15
+ ```
16
+
17
+ ```tsx
18
+ import { CredlyBadges } from 'react-credly-badges';
19
+
20
+ <CredlyBadges username="ahamed-safnaj" direction="horizontal" />;
21
+ ```
22
+
23
+ Use `direction="vertical"` for a column.
24
+
25
+ ## Development
26
+
27
+ Use Node.js 24 and npm. The tooling also supports Node.js 22.14
28
+ or newer on the Node.js 22 line.
29
+
30
+ ```sh
31
+ npm ci
32
+ npm run typecheck
33
+ npm run lint
34
+ npm run build
35
+ npm pack --dry-run
36
+ ```
37
+
38
+ There is currently no automated test suite. CI checks types, linting, the build,
39
+ and the package contents. Only the built library and package documentation are published;
40
+ the Cloudflare Worker is deployed separately and is not shipped in the npm package.
41
+ `prepack` runs typechecking, linting, and the build before packing or publishing.
42
+
43
+ The commitlint and release workflows select Node.js 24 directly. If you use nvm
44
+ locally, run `nvm install 24` and `nvm use 24`.
45
+
46
+ ### Commit conventions
47
+
48
+ `npm ci` installs the Husky `commit-msg` hook. Commitlint enforces
49
+ [Conventional Commits](https://www.conventionalcommits.org/), for example:
50
+
51
+ ```text
52
+ feat: add a badge size option
53
+ fix: handle an empty badge response
54
+ docs: clarify worker configuration
55
+ feat!: change the component API
56
+ ```
57
+
58
+ `fix` commits produce patch releases, `feat` commits produce minor releases, and
59
+ breaking changes (`!` or a `BREAKING CHANGE:` footer) produce major releases.
60
+ Other commit types do not trigger a release by default. PR commits and PR titles
61
+ are checked in CI. Prefer squash merges and preserve the validated PR title and
62
+ any breaking-change footer in the final commit message.
63
+
64
+ To check a message manually:
65
+
66
+ ```sh
67
+ printf '%s\n' 'feat: add a badge size option' | npm run commitlint
68
+ ```
69
+
70
+ ## Releases
71
+
72
+ The [CI workflow](.github/workflows/ci.yml) runs typechecking, linting, package
73
+ builds, and package inspection on Node.js 22 and 24 for pull requests.
74
+ The separate [Release workflow](.github/workflows/release.yml) runs on pushes to
75
+ `main` and calls the same reusable CI workflow before publishing. After both
76
+ matrix CI jobs pass, semantic-release analyzes commits, selects the next version,
77
+ publishes to npm, and creates a Git tag and GitHub release with generated release
78
+ notes. PRs never publish. The Release workflow can also be run manually on `main`
79
+ to retry a release; commits without a release-worthy change do not publish a new version.
80
+
81
+ Versions are written into the published package during release, not committed
82
+ back to `main`. Git tags and npm are the source of truth for released versions;
83
+ do not manually bump the source version for subsequent releases. No release
84
+ commits or personal GitHub access tokens are needed.
85
+
86
+ ### One-time maintainer setup
87
+
88
+ 1. Keep this GitHub repository public so npm can generate provenance. Enable
89
+ GitHub Actions and protect `main`, requiring both matrix CI checks and
90
+ `Conventional commits` before merging. Restrict direct pushes.
91
+ 2. The npm package must exist before its trusted publisher can be configured.
92
+ For this unpublished package, sign in with an npm account that can publish
93
+ `react-credly-badges`, and bootstrap the current version once:
94
+
95
+ ```sh
96
+ npm ci
97
+ npm login
98
+ npm publish --access public
99
+ git tag v0.1.0
100
+ git push origin v0.1.0
101
+ ```
102
+
103
+ Run this from a clean, committed checkout on `main`, before enabling the
104
+ first automated release. Tag the exact commit used to publish. If a version
105
+ already exists on npm, instead ensure its corresponding Git tag is present;
106
+ do not publish it again. The bootstrap tag tells semantic-release where
107
+ the existing release history starts. Without any release tags,
108
+ semantic-release's first release defaults to `1.0.0`.
109
+ 3. In the npm package settings, add a **GitHub Actions trusted publisher** with:
110
+ - Organization or user: `Safnaj`
111
+ - Repository: `react-credly-badges`
112
+ - Workflow filename: `release.yml` (the caller workflow that publishes).
113
+ - Environment: leave blank (the release job does not use an environment).
114
+ 4. After verifying trusted publishing, disable token-based publishing in the
115
+ npm package settings where available. No `NPM_TOKEN` secret is required:
116
+ the release job uses OIDC (`id-token: write`), and npm automatically attaches
117
+ provenance. GitHub releases use the built-in `GITHUB_TOKEN`, with write
118
+ access limited to the release job.
119
+ 5. Merge a release-worthy Conventional Commit into `main` or manually run the
120
+ workflow after setup. Do not run `npm run release` locally to publish;
121
+ trusted publishing is authorized only from the configured GitHub workflow.
122
+
123
+ ## License
124
+
125
+ This package is currently unlicensed (`UNLICENSED`); no open-source license or
126
+ permission to reuse the code is granted. Choose a license before distributing
127
+ it as an open-source library.
128
+
129
+ ## Note
130
+
131
+ This is an unofficial integration that displays public badges only.
132
+ Your username is sent to the hosted Worker to retrieve badges.
@@ -0,0 +1,160 @@
1
+ "use client";
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var src_exports = {};
33
+ __export(src_exports, {
34
+ CredlyBadges: () => CredlyBadges
35
+ });
36
+ module.exports = __toCommonJS(src_exports);
37
+
38
+ // src/components/CredlyBadges.tsx
39
+ var React = __toESM(require("react"), 1);
40
+
41
+ // src/shared/badges.ts
42
+ function isRecord(value) {
43
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44
+ }
45
+ function isNonEmptyString(value) {
46
+ return typeof value === "string" && value.trim().length > 0;
47
+ }
48
+ function isHttpsUrl(value) {
49
+ if (!isNonEmptyString(value)) return false;
50
+ try {
51
+ return new URL(value).protocol === "https:";
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+ function parseBadges(value) {
57
+ const isWorkerResponse = isRecord(value);
58
+ const badges = isWorkerResponse ? value.badges : value;
59
+ if (!Array.isArray(badges)) {
60
+ throw new Error("The badges endpoint must return a JSON array or an object with a badges array.");
61
+ }
62
+ return badges.map((badge) => {
63
+ const url = isRecord(badge) ? isWorkerResponse ? badge.badgeUrl : badge.url : void 0;
64
+ if (!isRecord(badge) || !isNonEmptyString(badge.id) || !isNonEmptyString(badge.name) || !isHttpsUrl(badge.imageUrl) || !isHttpsUrl(url)) {
65
+ throw new Error("The badges endpoint returned an invalid badge.");
66
+ }
67
+ return {
68
+ id: badge.id,
69
+ name: badge.name,
70
+ imageUrl: badge.imageUrl,
71
+ url
72
+ };
73
+ });
74
+ }
75
+
76
+ // src/components/CredlyBadges.tsx
77
+ function CredlyBadges({
78
+ username,
79
+ direction = "horizontal",
80
+ endpoint = "https://react-credly-badges.safnaj99.workers.dev/",
81
+ className,
82
+ style
83
+ }) {
84
+ const key = JSON.stringify([username, endpoint]);
85
+ const [state, setState] = React.useState({
86
+ key,
87
+ status: "loading"
88
+ });
89
+ React.useEffect(() => {
90
+ const controller = new AbortController();
91
+ let active = true;
92
+ setState({ key, status: "loading" });
93
+ async function loadBadges() {
94
+ try {
95
+ if (!username.trim()) {
96
+ throw new Error("A Credly username is required.");
97
+ }
98
+ const url = new URL(endpoint, window.location.href);
99
+ url.searchParams.set("username", username.trim());
100
+ const response = await fetch(url, {
101
+ headers: { Accept: "application/json" },
102
+ signal: controller.signal
103
+ });
104
+ if (!response.ok) {
105
+ throw new Error(
106
+ `Unable to load Credly badges (HTTP ${response.status}).`
107
+ );
108
+ }
109
+ const payload = await response.json();
110
+ const badges = parseBadges(payload);
111
+ if (active) setState({ key, status: "success", badges });
112
+ } catch (error) {
113
+ if (active) {
114
+ setState({
115
+ key,
116
+ status: "error",
117
+ message: error instanceof Error ? error.message : "Unable to load Credly badges."
118
+ });
119
+ }
120
+ }
121
+ }
122
+ void loadBadges();
123
+ return () => {
124
+ active = false;
125
+ controller.abort();
126
+ };
127
+ }, [username, endpoint, key]);
128
+ const current = state.key === key ? state : { key, status: "loading" };
129
+ return /* @__PURE__ */ React.createElement("div", { className, style }, current.status === "loading" && /* @__PURE__ */ React.createElement("p", { role: "status" }, "Loading Credly badges..."), current.status === "error" && /* @__PURE__ */ React.createElement("p", { role: "alert" }, current.message), current.status === "success" && (current.badges.length === 0 ? /* @__PURE__ */ React.createElement("p", { role: "status" }, "No public Credly badges found.") : /* @__PURE__ */ React.createElement(
130
+ "ul",
131
+ {
132
+ "aria-label": `Credly badges for ${username}`,
133
+ style: {
134
+ display: "flex",
135
+ flexDirection: direction === "vertical" ? "column" : "row",
136
+ flexWrap: direction === "vertical" ? "nowrap" : "wrap",
137
+ gap: "1rem",
138
+ listStyle: "none",
139
+ margin: 0,
140
+ padding: 0
141
+ }
142
+ },
143
+ current.badges.map((badge) => /* @__PURE__ */ React.createElement("li", { key: badge.id }, /* @__PURE__ */ React.createElement("a", { href: badge.url, target: "_blank", rel: "noopener noreferrer" }, /* @__PURE__ */ React.createElement(
144
+ "img",
145
+ {
146
+ src: badge.imageUrl,
147
+ alt: badge.name,
148
+ width: 120,
149
+ height: 120,
150
+ loading: "lazy",
151
+ style: { objectFit: "contain" }
152
+ }
153
+ ))))
154
+ )));
155
+ }
156
+ // Annotate the CommonJS export names for ESM import in node:
157
+ 0 && (module.exports = {
158
+ CredlyBadges
159
+ });
160
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/components/CredlyBadges.tsx","../../src/shared/badges.ts"],"sourcesContent":["export { CredlyBadges } from './components/CredlyBadges';\nexport type { CredlyBadgesProps } from './components/CredlyBadges';\nexport type { CredlyBadge } from './shared/badges';\n","import * as React from \"react\";\nimport type { CSSProperties } from \"react\";\nimport { parseBadges } from \"../shared/badges\";\nimport type { CredlyBadge } from \"../shared/badges\";\n\nexport interface CredlyBadgesProps {\n username: string;\n direction?: \"horizontal\" | \"vertical\";\n endpoint?: string;\n className?: string;\n style?: CSSProperties;\n}\n\ntype BadgeState =\n | { key: string; status: \"loading\" }\n | { key: string; status: \"success\"; badges: CredlyBadge[] }\n | { key: string; status: \"error\"; message: string };\n\nexport function CredlyBadges({\n username,\n direction = \"horizontal\",\n endpoint = \"https://react-credly-badges.safnaj99.workers.dev/\",\n className,\n style,\n}: CredlyBadgesProps) {\n const key = JSON.stringify([username, endpoint]);\n const [state, setState] = React.useState<BadgeState>({\n key,\n status: \"loading\",\n });\n\n React.useEffect(() => {\n const controller = new AbortController();\n let active = true;\n setState({ key, status: \"loading\" });\n\n async function loadBadges() {\n try {\n if (!username.trim()) {\n throw new Error(\"A Credly username is required.\");\n }\n\n const url = new URL(endpoint, window.location.href);\n url.searchParams.set(\"username\", username.trim());\n const response = await fetch(url, {\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(\n `Unable to load Credly badges (HTTP ${response.status}).`,\n );\n }\n\n const payload: unknown = await response.json();\n const badges = parseBadges(payload);\n if (active) setState({ key, status: \"success\", badges });\n } catch (error: unknown) {\n if (active) {\n setState({\n key,\n status: \"error\",\n message:\n error instanceof Error\n ? error.message\n : \"Unable to load Credly badges.\",\n });\n }\n }\n }\n\n void loadBadges();\n\n return () => {\n active = false;\n controller.abort();\n };\n }, [username, endpoint, key]);\n\n // Hide results from the previous profile before the next effect runs.\n const current: BadgeState =\n state.key === key ? state : { key, status: \"loading\" };\n\n return (\n <div className={className} style={style}>\n {current.status === \"loading\" && (\n <p role='status'>Loading Credly badges...</p>\n )}\n {current.status === \"error\" && <p role='alert'>{current.message}</p>}\n {current.status === \"success\" &&\n (current.badges.length === 0 ? (\n <p role='status'>No public Credly badges found.</p>\n ) : (\n <ul\n aria-label={`Credly badges for ${username}`}\n style={{\n display: \"flex\",\n flexDirection: direction === \"vertical\" ? \"column\" : \"row\",\n flexWrap: direction === \"vertical\" ? \"nowrap\" : \"wrap\",\n gap: \"1rem\",\n listStyle: \"none\",\n margin: 0,\n padding: 0,\n }}\n >\n {current.badges.map((badge) => (\n <li key={badge.id}>\n <a href={badge.url} target='_blank' rel='noopener noreferrer'>\n <img\n src={badge.imageUrl}\n alt={badge.name}\n width={120}\n height={120}\n loading='lazy'\n style={{ objectFit: \"contain\" }}\n />\n </a>\n </li>\n ))}\n </ul>\n ))}\n </div>\n );\n}\n","export interface CredlyBadge {\n id: string;\n name: string;\n imageUrl: string;\n url: string;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\nexport function isHttpsUrl(value: unknown): value is string {\n if (!isNonEmptyString(value)) return false;\n\n try {\n return new URL(value).protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function parseBadges(value: unknown): CredlyBadge[] {\n const isWorkerResponse = isRecord(value);\n const badges: unknown = isWorkerResponse ? value.badges : value;\n\n if (!Array.isArray(badges)) {\n throw new Error('The badges endpoint must return a JSON array or an object with a badges array.');\n }\n\n return badges.map((badge: unknown) => {\n const url = isRecord(badge)\n ? (isWorkerResponse ? badge.badgeUrl : badge.url)\n : undefined;\n\n if (\n !isRecord(badge) ||\n !isNonEmptyString(badge.id) ||\n !isNonEmptyString(badge.name) ||\n !isHttpsUrl(badge.imageUrl) ||\n !isHttpsUrl(url)\n ) {\n throw new Error('The badges endpoint returned an invalid badge.');\n }\n\n return {\n id: badge.id,\n name: badge.name,\n imageUrl: badge.imageUrl,\n url,\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,YAAuB;;;ACOhB,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEO,SAAS,iBAAiB,OAAiC;AAChE,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS;AAC5D;AAEO,SAAS,WAAW,OAAiC;AAC1D,MAAI,CAAC,iBAAiB,KAAK,EAAG,QAAO;AAErC,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,EAAE,aAAa;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,YAAY,OAA+B;AACzD,QAAM,mBAAmB,SAAS,KAAK;AACvC,QAAM,SAAkB,mBAAmB,MAAM,SAAS;AAE1D,MAAI,CAAC,MAAM,QAAQ,MAAM,GAAG;AAC1B,UAAM,IAAI,MAAM,gFAAgF;AAAA,EAClG;AAEA,SAAO,OAAO,IAAI,CAAC,UAAmB;AACpC,UAAM,MAAM,SAAS,KAAK,IACrB,mBAAmB,MAAM,WAAW,MAAM,MAC3C;AAEJ,QACE,CAAC,SAAS,KAAK,KACf,CAAC,iBAAiB,MAAM,EAAE,KAC1B,CAAC,iBAAiB,M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lyBadgesProps {
5
+ username: string;
6
+ direction?: "horizontal" | "vertical";
7
+ endpoint?: string;
8
+ className?: string;
9
+ style?: CSSProperties;
10
+ }
11
+ declare function CredlyBadges({ username, direction, endpoint, className, style, }: CredlyBadgesProps): React.JSX.Element;
12
+
13
+ interface CredlyBadge {
14
+ id: string;
15
+ name: string;
16
+ imageUrl: string;
17
+ url: string;
18
+ }
19
+
20
+ export { CredlyBadges };
21
+ export type { CredlyBadge, CredlyBadgesProps };
@@ -0,0 +1,21 @@
1
+ import * as React from 'react';
2
+ import { CSSProperties } from 'react';
3
+
4
+ interface CredlyBadgesProps {
5
+ username: string;
6
+ direction?: "horizontal" | "vertical";
7
+ endpoint?: string;
8
+ className?: string;
9
+ style?: CSSProperties;
10
+ }
11
+ declare function CredlyBadges({ username, direction, endpoint, className, style, }: CredlyBadgesProps): React.JSX.Element;
12
+
13
+ interface CredlyBadge {
14
+ id: string;
15
+ name: string;
16
+ imageUrl: string;
17
+ url: string;
18
+ }
19
+
20
+ export { CredlyBadges };
21
+ export type { CredlyBadge, CredlyBadgesProps };
@@ -0,0 +1,124 @@
1
+ "use client";
2
+
3
+ // src/components/CredlyBadges.tsx
4
+ import * as React from "react";
5
+
6
+ // src/shared/badges.ts
7
+ function isRecord(value) {
8
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9
+ }
10
+ function isNonEmptyString(value) {
11
+ return typeof value === "string" && value.trim().length > 0;
12
+ }
13
+ function isHttpsUrl(value) {
14
+ if (!isNonEmptyString(value)) return false;
15
+ try {
16
+ return new URL(value).protocol === "https:";
17
+ } catch {
18
+ return false;
19
+ }
20
+ }
21
+ function parseBadges(value) {
22
+ const isWorkerResponse = isRecord(value);
23
+ const badges = isWorkerResponse ? value.badges : value;
24
+ if (!Array.isArray(badges)) {
25
+ throw new Error("The badges endpoint must return a JSON array or an object with a badges array.");
26
+ }
27
+ return badges.map((badge) => {
28
+ const url = isRecord(badge) ? isWorkerResponse ? badge.badgeUrl : badge.url : void 0;
29
+ if (!isRecord(badge) || !isNonEmptyString(badge.id) || !isNonEmptyString(badge.name) || !isHttpsUrl(badge.imageUrl) || !isHttpsUrl(url)) {
30
+ throw new Error("The badges endpoint returned an invalid badge.");
31
+ }
32
+ return {
33
+ id: badge.id,
34
+ name: badge.name,
35
+ imageUrl: badge.imageUrl,
36
+ url
37
+ };
38
+ });
39
+ }
40
+
41
+ // src/components/CredlyBadges.tsx
42
+ function CredlyBadges({
43
+ username,
44
+ direction = "horizontal",
45
+ endpoint = "https://react-credly-badges.safnaj99.workers.dev/",
46
+ className,
47
+ style
48
+ }) {
49
+ const key = JSON.stringify([username, endpoint]);
50
+ const [state, setState] = React.useState({
51
+ key,
52
+ status: "loading"
53
+ });
54
+ React.useEffect(() => {
55
+ const controller = new AbortController();
56
+ let active = true;
57
+ setState({ key, status: "loading" });
58
+ async function loadBadges() {
59
+ try {
60
+ if (!username.trim()) {
61
+ throw new Error("A Credly username is required.");
62
+ }
63
+ const url = new URL(endpoint, window.location.href);
64
+ url.searchParams.set("username", username.trim());
65
+ const response = await fetch(url, {
66
+ headers: { Accept: "application/json" },
67
+ signal: controller.signal
68
+ });
69
+ if (!response.ok) {
70
+ throw new Error(
71
+ `Unable to load Credly badges (HTTP ${response.status}).`
72
+ );
73
+ }
74
+ const payload = await response.json();
75
+ const badges = parseBadges(payload);
76
+ if (active) setState({ key, status: "success", badges });
77
+ } catch (error) {
78
+ if (active) {
79
+ setState({
80
+ key,
81
+ status: "error",
82
+ message: error instanceof Error ? error.message : "Unable to load Credly badges."
83
+ });
84
+ }
85
+ }
86
+ }
87
+ void loadBadges();
88
+ return () => {
89
+ active = false;
90
+ controller.abort();
91
+ };
92
+ }, [username, endpoint, key]);
93
+ const current = state.key === key ? state : { key, status: "loading" };
94
+ return /* @__PURE__ */ React.createElement("div", { className, style }, current.status === "loading" && /* @__PURE__ */ React.createElement("p", { role: "status" }, "Loading Credly badges..."), current.status === "error" && /* @__PURE__ */ React.createElement("p", { role: "alert" }, current.message), current.status === "success" && (current.badges.length === 0 ? /* @__PURE__ */ React.createElement("p", { role: "status" }, "No public Credly badges found.") : /* @__PURE__ */ React.createElement(
95
+ "ul",
96
+ {
97
+ "aria-label": `Credly badges for ${username}`,
98
+ style: {
99
+ display: "flex",
100
+ flexDirection: direction === "vertical" ? "column" : "row",
101
+ flexWrap: direction === "vertical" ? "nowrap" : "wrap",
102
+ gap: "1rem",
103
+ listStyle: "none",
104
+ margin: 0,
105
+ padding: 0
106
+ }
107
+ },
108
+ current.badges.map((badge) => /* @__PURE__ */ React.createElement("li", { key: badge.id }, /* @__PURE__ */ React.createElement("a", { href: badge.url, target: "_blank", rel: "noopener noreferrer" }, /* @__PURE__ */ React.createElement(
109
+ "img",
110
+ {
111
+ src: badge.imageUrl,
112
+ alt: badge.name,
113
+ width: 120,
114
+ height: 120,
115
+ loading: "lazy",
116
+ style: { objectFit: "contain" }
117
+ }
118
+ ))))
119
+ )));
120
+ }
121
+ export {
122
+ CredlyBadges
123
+ };
124
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/components/CredlyBadges.tsx","../../src/shared/badges.ts"],"sourcesContent":["import * as React from \"react\";\nimport type { CSSProperties } from \"react\";\nimport { parseBadges } from \"../shared/badges\";\nimport type { CredlyBadge } from \"../shared/badges\";\n\nexport interface CredlyBadgesProps {\n username: string;\n direction?: \"horizontal\" | \"vertical\";\n endpoint?: string;\n className?: string;\n style?: CSSProperties;\n}\n\ntype BadgeState =\n | { key: string; status: \"loading\" }\n | { key: string; status: \"success\"; badges: CredlyBadge[] }\n | { key: string; status: \"error\"; message: string };\n\nexport function CredlyBadges({\n username,\n direction = \"horizontal\",\n endpoint = \"https://react-credly-badges.safnaj99.workers.dev/\",\n className,\n style,\n}: CredlyBadgesProps) {\n const key = JSON.stringify([username, endpoint]);\n const [state, setState] = React.useState<BadgeState>({\n key,\n status: \"loading\",\n });\n\n React.useEffect(() => {\n const controller = new AbortController();\n let active = true;\n setState({ key, status: \"loading\" });\n\n async function loadBadges() {\n try {\n if (!username.trim()) {\n throw new Error(\"A Credly username is required.\");\n }\n\n const url = new URL(endpoint, window.location.href);\n url.searchParams.set(\"username\", username.trim());\n const response = await fetch(url, {\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n\n if (!response.ok) {\n throw new Error(\n `Unable to load Credly badges (HTTP ${response.status}).`,\n );\n }\n\n const payload: unknown = await response.json();\n const badges = parseBadges(payload);\n if (active) setState({ key, status: \"success\", badges });\n } catch (error: unknown) {\n if (active) {\n setState({\n key,\n status: \"error\",\n message:\n error instanceof Error\n ? error.message\n : \"Unable to load Credly badges.\",\n });\n }\n }\n }\n\n void loadBadges();\n\n return () => {\n active = false;\n controller.abort();\n };\n }, [username, endpoint, key]);\n\n // Hide results from the previous profile before the next effect runs.\n const current: BadgeState =\n state.key === key ? state : { key, status: \"loading\" };\n\n return (\n <div className={className} style={style}>\n {current.status === \"loading\" && (\n <p role='status'>Loading Credly badges...</p>\n )}\n {current.status === \"error\" && <p role='alert'>{current.message}</p>}\n {current.status === \"success\" &&\n (current.badges.length === 0 ? (\n <p role='status'>No public Credly badges found.</p>\n ) : (\n <ul\n aria-label={`Credly badges for ${username}`}\n style={{\n display: \"flex\",\n flexDirection: direction === \"vertical\" ? \"column\" : \"row\",\n flexWrap: direction === \"vertical\" ? \"nowrap\" : \"wrap\",\n gap: \"1rem\",\n listStyle: \"none\",\n margin: 0,\n padding: 0,\n }}\n >\n {current.badges.map((badge) => (\n <li key={badge.id}>\n <a href={badge.url} target='_blank' rel='noopener noreferrer'>\n <img\n src={badge.imageUrl}\n alt={badge.name}\n width={120}\n height={120}\n loading='lazy'\n style={{ objectFit: \"contain\" }}\n />\n </a>\n </li>\n ))}\n </ul>\n ))}\n </div>\n );\n}\n","export interface CredlyBadge {\n id: string;\n name: string;\n imageUrl: string;\n url: string;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function isNonEmptyString(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\n\nexport function isHttpsUrl(value: unknown): value is string {\n if (!isNonEmptyString(value)) return false;\n\n try {\n return new URL(value).protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nexport function parseBadges(value: unknown): CredlyBadge[] {\n const isWorkerResponse = isRecord(value);\n const badges: unknown = isWorkerResponse ? value.badges : value;\n\n if (!Array.isArray(badges)) {\n throw new Error('The badges endpoint must return a JSON array or an object with a badges array.');\n }\n\n return badges.map((badge: unknown) => {\n const url = isRecord(badge)\n ? (isWorkerResponse ? badge.badgeUrl : badge.url)\n : undefined;\n\n if (\n !isRecord(badge) ||\n !isNonEmptyString(badge.id) ||\n !isNonEmptyString(badge.name) ||\n !isHttpsUrl(badge.imageUrl) ||\n !isHttpsUrl(url)\n ) {\n throw new Error('The badges endpoint returned an invalid badge.');\n }\n\n return {\n id: badge.id,\n name: badge.name,\n imageUrl: badge.imageUrl,\n url,\n };\n });\n}\n"],"mappings":";;;AAAA,YAAY,WAAW;;;ACOhB,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEO,SAAS,iBAAiB,OAAiC;AAChE,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS;AAC5D;AAEO,SAAS,WAAW,OAAiC;AAC1D,MAAI,CAAC,iBAAiB,KAAK,EAAG,QAAO;AAErC,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,EAAE,aAAa;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,YAAY,OAA+B;AACzD,QAAM,mBAAmB,SAAS,KAAK;AACvC,QAAM,SAAkB,mBAAmB,MAAM,SAAS;AAE1D,MAAI,CAAC,MAAM,QAAQ,MAAM,GAAG;AAC1B,UAAM,IAAI,MAAM,gFAAgF;AAAA,EAClG;AAEA,SAAO,OAAO,IAAI,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QACR,OAAO,EAAE,WAAW,UAAU;AAAA;AAAA,IAChC,CACF,CACF,CACD;AAAA,EACH,EAEN;AAEJ;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "react-credly-badges",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A lightweight React component for displaying public Credly badges through a Cloudflare Worker.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "./dist/client/index.cjs",
8
+ "module": "./dist/client/index.js",
9
+ "types": "./dist/client/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/client/index.d.ts",
14
+ "default": "./dist/client/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/client/index.d.cts",
18
+ "default": "./dist/client/index.cjs"
19
+ }
20
+ }
21
+ },
22
+ "files": ["dist"],
23
+ "sideEffects": false,
24
+ "scripts": {
25
+ "build": "tsup",
26
+ "dev": "tsup --watch",
27
+ "typecheck": "tsc --noEmit",
28
+ "lint": "eslint .",
29
+ "commitlint": "commitlint",
30
+ "release": "semantic-release",
31
+ "prepare": "husky",
32
+ "prepack": "npm run typecheck && npm run lint && npm run build"
33
+ },
34
+ "peerDependencies": {
35
+ "react": "^17.0.0 || ^18.2.0 || ^19.0.0"
36
+ },
37
+ "devDependencies": {
38
+ "@commitlint/cli": "^21.2.4",
39
+ "@commitlint/config-conventional": "^21.2.4",
40
+ "@eslint/js": "^10.0.0",
41
+ "@semantic-release/commit-analyzer": "^13.0.1",
42
+ "@semantic-release/github": "^12.0.10",
43
+ "@semantic-release/npm": "^13.2.0",
44
+ "@semantic-release/release-notes-generator": "^14.1.1",
45
+ "@types/react": "^19.0.0",
46
+ "eslint": "^10.0.0",
47
+ "eslint-plugin-react-hooks": "^7.0.0",
48
+ "globals": "^16.0.0",
49
+ "husky": "^9.1.7",
50
+ "react": "^19.0.0",
51
+ "semantic-release": "^25.0.9",
52
+ "tsup": "^9.0.0",
53
+ "typescript": "~5.9.3",
54
+ "typescript-eslint": "^8.0.0"
55
+ },
56
+ "keywords": ["react", "credly", "badges", "typescript"],
57
+ "publishConfig": {
58
+ "access": "public",
59
+ "registry": "https://registry.npmjs.org/"
60
+ },
61
+ "homepage": "https://github.com/Safnaj/react-credly-badges#readme",
62
+ "bugs": {
63
+ "url": "https://github.com/Safnaj/react-credly-badges/issues"
64
+ },
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "git+https://github.com/Safnaj/react-credly-badges.git"
68
+ }
69
+ }