@cardware/cardware-link 0.1.0 → 0.2.1

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
@@ -14,8 +14,8 @@ npm install @cardware/cardware-link
14
14
  | `@cardware/cardware-link/payload/admin` | The plugin's admin component, loaded through Payload's import map. |
15
15
  | `@cardware/cardware-link/payload/client` | The browser helper that reports saves from a page a link opened. No deps. |
16
16
 
17
- `payload` and `react` are optional peer dependencies, needed only for the plugin; a client-only install pulls in
18
- nothing else.
17
+ `payload`, `@payloadcms/ui` and `react` are optional peer dependencies, needed only for the plugin; a client-only
18
+ install pulls in nothing else.
19
19
 
20
20
  ## The client
21
21
 
@@ -41,7 +41,12 @@ types. Every method, and the API it calls, is described in the
41
41
  import { cardwareLinkPlugin } from '@cardware/cardware-link/payload'
42
42
 
43
43
  cardwareLinkPlugin({
44
- access: { manage: ({ req }) => Boolean(req.user?.roles?.includes('admin')) },
44
+ access: {
45
+ manage: ({ req }) => Boolean(req.user?.roles?.includes('admin')),
46
+ // Optional: the links collection's create/read/update/delete rules, in place of the plugin's, for a host that
47
+ // keeps every rule in one table.
48
+ collection: policy['tracked-links'],
49
+ },
45
50
  admin: { group: 'CardWare' },
46
51
  collections: {
47
52
  employees: {
@@ -87,7 +92,9 @@ What it adds:
87
92
  it on demand. Payload runs scheduled jobs only where crons are on: call `getPayload({ config, cron: true })` once on
88
93
  the server, for example from Next's `instrumentation.ts`.
89
94
  - **The link's admin screen** (`@cardware/cardware-link/payload/admin#LinkPanel`; run `payload generate:importmap`):
90
- the code, the URL, live totals from `GET /v1/links/:key`, and SVG and PNG downloads.
95
+ the code, the URL with a copy button, live totals from `GET /v1/links/:key`, and SVG and PNG downloads. Built from
96
+ `@payloadcms/ui` (`Banner`, `Button`, `CopyToClipboard`) and Payload's design tokens, in its `payload-default`
97
+ layer, so it follows the admin's light and dark themes.
91
98
  - **Endpoints:**
92
99
  - `GET /api/tracked-links/:id/code?format=svg|png&size=&mm=&dpi=&download=1`, for users who may read the link: the
93
100
  service's code, fetched with the app key, so the key never reaches the browser.
@@ -0,0 +1,80 @@
1
+ @layer payload-default {
2
+ .cardware-link-panel__card {
3
+ display: flex;
4
+ flex-wrap: wrap;
5
+ background: var(--color-bg-secondary);
6
+ border: var(--stroke-width-small) solid var(--color-border);
7
+ border-radius: var(--radius-medium);
8
+ gap: var(--spacer-4);
9
+ padding: var(--spacer-4);
10
+ }
11
+
12
+ .cardware-link-panel__code {
13
+ display: block;
14
+ flex-shrink: 0;
15
+ width: calc(var(--spacer-6) * 4.5);
16
+ height: calc(var(--spacer-6) * 4.5);
17
+ border: var(--stroke-width-small) solid var(--color-border);
18
+ border-radius: var(--radius-small);
19
+ overflow: hidden;
20
+ }
21
+
22
+ .cardware-link-panel__details {
23
+ display: flex;
24
+ flex-direction: column;
25
+ flex: 1 1 280px;
26
+ min-width: 0;
27
+ gap: var(--spacer-3);
28
+ }
29
+
30
+ .cardware-link-panel__totals {
31
+ display: flex;
32
+ flex-wrap: wrap;
33
+ gap: var(--spacer-5);
34
+ margin: 0;
35
+ }
36
+
37
+ .cardware-link-panel__total dt {
38
+ color: var(--color-text-secondary);
39
+ font-size: var(--text-body-medium-font-size);
40
+ font-weight: var(--text-body-medium-font-weight);
41
+ line-height: var(--text-body-medium-line-height);
42
+ }
43
+
44
+ .cardware-link-panel__total dd {
45
+ margin: 0;
46
+ font-size: var(--text-heading-xl-font-size);
47
+ font-weight: var(--text-heading-xl-font-weight);
48
+ line-height: var(--text-heading-xl-line-height);
49
+ font-variant-numeric: tabular-nums;
50
+ }
51
+
52
+ .cardware-link-panel__source {
53
+ margin: 0;
54
+ color: var(--color-text-secondary);
55
+ font-size: var(--text-body-medium-font-size);
56
+ line-height: var(--text-body-medium-line-height);
57
+ }
58
+
59
+ .cardware-link-panel__url {
60
+ display: flex;
61
+ align-items: center;
62
+ gap: var(--spacer-2);
63
+ min-width: 0;
64
+ }
65
+
66
+ .cardware-link-panel__url code {
67
+ overflow: hidden;
68
+ text-overflow: ellipsis;
69
+ white-space: nowrap;
70
+ font-family: var(--text-mono-family), monospace;
71
+ font-size: var(--text-mono-medium-font-size);
72
+ line-height: var(--text-mono-medium-line-height);
73
+ }
74
+
75
+ .cardware-link-panel__downloads {
76
+ display: flex;
77
+ flex-wrap: wrap;
78
+ gap: var(--spacer-2);
79
+ }
80
+ }
@@ -1,4 +1,5 @@
1
1
  import type { UIFieldServerProps } from 'payload';
2
+ import './link-panel.css';
2
3
  /**
3
4
  * The link's code, its URL, its live totals and downloads of the code. Rendered on the server: the totals are read
4
5
  * from the service here, and the code is an image from the plugin's code endpoint, so the app key never reaches the
@@ -1,9 +1,11 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Banner, Button, CopyToClipboard } from '@payloadcms/ui';
2
3
  import { resolvedOf } from '../options.js';
3
4
  import { LINKS } from '../types.js';
5
+ import './link-panel.css';
4
6
  /** A thermal label printer's resolution. */
5
7
  const LABEL_DPI = 203;
6
- const button = 'btn btn--style-secondary btn--size-small btn--icon-style-without-border';
8
+ const baseClass = 'cardware-link-panel';
7
9
  /**
8
10
  * The link's code, its URL, its live totals and downloads of the code. Rendered on the server: the totals are read
9
11
  * from the service here, and the code is an image from the plugin's code endpoint, so the app key never reaches the
@@ -36,5 +38,10 @@ export async function LinkPanel({ data, payload }) {
36
38
  ['Unique scanners', totals.uniqueScanners],
37
39
  ['Saves', totals.saves],
38
40
  ];
39
- return (_jsxs("div", { className: "field-type", "data-cardware-link-panel": "", style: { display: 'flex', flexWrap: 'wrap', gap: 24, alignItems: 'center', marginBottom: 24 }, children: [_jsx("img", { src: `${code}?format=svg`, alt: `Code for ${url}`, width: 180, height: 180 }), _jsxs("div", { style: { display: 'grid', gap: 12 }, children: [_jsx("dl", { style: { display: 'flex', gap: 24, margin: 0 }, children: stats.map(([label, value]) => (_jsxs("div", { "data-total": label, children: [_jsx("dt", { style: { opacity: 0.7 }, children: label }), _jsx("dd", { style: { margin: 0, fontSize: '1.75rem', fontWeight: 600 }, children: value })] }, label))) }), _jsx("p", { style: { margin: 0, opacity: 0.7 }, children: live ? 'Live from cardware.link.' : `Copied counts. ${problem ?? ''}` }), _jsx("code", { children: url }), (live?.retired ?? data.retired) ? _jsx("p", { style: { margin: 0 }, children: "Retired: not counting." }) : null, _jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 8 }, children: [_jsx("a", { className: button, href: `${code}?format=svg&download=1`, download: true, children: "SVG for print" }), _jsx("a", { className: button, href: `${code}?format=png&size=1024&download=1`, download: true, children: "PNG 1024 px" }), _jsxs("a", { className: button, href: `${code}?format=png&mm=25&dpi=${LABEL_DPI}&download=1`, download: true, children: ["Label PNG, 25 mm at ", LABEL_DPI, " dpi"] })] })] })] }));
41
+ const downloads = [
42
+ ['SVG for print', `${code}?format=svg&download=1`],
43
+ ['PNG 1024 px', `${code}?format=png&size=1024&download=1`],
44
+ [`Label PNG, 25 mm at ${LABEL_DPI} dpi`, `${code}?format=png&mm=25&dpi=${LABEL_DPI}&download=1`],
45
+ ];
46
+ return (_jsx("div", { className: `field-type ${baseClass}`, children: _jsxs("div", { className: `${baseClass}__card`, children: [_jsx("img", { className: `${baseClass}__code`, src: `${code}?format=svg`, alt: `Code for ${url}` }), _jsxs("div", { className: `${baseClass}__details`, children: [(live?.retired ?? data.retired) ? (_jsx(Banner, { children: "Retired: the link still opens its destination and counts nothing." })) : null, problem ? _jsxs(Banner, { type: "warning", children: ["Showing the copied counts. ", problem] }) : null, _jsx("dl", { className: `${baseClass}__totals`, children: stats.map(([label, value]) => (_jsxs("div", { className: `${baseClass}__total`, "data-total": label, children: [_jsx("dt", { children: label }), _jsx("dd", { children: value })] }, label))) }), live ? _jsx("p", { className: `${baseClass}__source`, children: "Live from cardware.link." }) : null, _jsxs("div", { className: `${baseClass}__url`, children: [_jsx("code", { children: url }), _jsx(CopyToClipboard, { value: url, defaultMessage: "Copy URL" })] }), _jsx("div", { className: `${baseClass}__downloads`, children: downloads.map(([label, href]) => (_jsx(Button, { el: "anchor", url: href, buttonStyle: "secondary", extraButtonProps: { download: true }, children: label }, label))) })] })] }) }));
40
47
  }
@@ -17,7 +17,9 @@ export declare const refuseDeleteWhileLinked: (relationTo: CollectionSlug) => ({
17
17
  }) => Promise<void>;
18
18
  /**
19
19
  * Moves each link whose stored destination no longer matches its document's to the document's current one, on the
20
- * service and then in the stored copy. Answers the failures; a later attempt starts again from the stored copies.
20
+ * service and then in the stored copy. Answers the moves the service refused; a later attempt starts again from the
21
+ * stored copies. A stored copy that cannot be written is not such a refusal: that error is thrown, because in a
22
+ * transaction nothing written after it would be kept.
21
23
  */
22
24
  export declare const moveLinks: (req: Pick<PayloadRequest, 'payload'> & Partial<PayloadRequest>, resolved: Resolved, next: string, links: Pick<StoredLink, 'id' | 'key' | 'destination'>[]) => Promise<string[]>;
23
25
  /**
@@ -105,6 +105,7 @@ export const linksCollection = (resolved) => ({
105
105
  create: ({ req }) => Boolean(req.user),
106
106
  update: ({ req }) => linksWhere(req, resolved),
107
107
  delete: ({ req }) => resolved.manages(req),
108
+ ...resolved.access,
108
109
  },
109
110
  versions: false,
110
111
  endpoints: endpoints(resolved),
@@ -246,25 +247,28 @@ export const refuseDeleteWhileLinked = (relationTo) => async ({ id, req }) => {
246
247
  };
247
248
  /**
248
249
  * Moves each link whose stored destination no longer matches its document's to the document's current one, on the
249
- * service and then in the stored copy. Answers the failures; a later attempt starts again from the stored copies.
250
+ * service and then in the stored copy. Answers the moves the service refused; a later attempt starts again from the
251
+ * stored copies. A stored copy that cannot be written is not such a refusal: that error is thrown, because in a
252
+ * transaction nothing written after it would be kept.
250
253
  */
251
254
  export const moveLinks = async (req, resolved, next, links) => {
252
255
  const failed = [];
253
256
  for (const link of links.filter((each) => each.key && each.destination !== next)) {
254
257
  try {
255
258
  await resolved.service('Not moved', (client) => client.update(link.key, { destination: next }));
256
- await req.payload.db.updateOne({
257
- collection: LINKS,
258
- id: link.id,
259
- data: { destination: next },
260
- returning: false,
261
- req,
262
- });
263
259
  }
264
260
  catch (error) {
265
261
  failed.push(error instanceof Error ? error.message : String(error));
266
262
  req.payload.logger.error({ err: error, msg: `cardware.link: link ${link.key} not moved to ${next}` });
263
+ continue;
267
264
  }
265
+ await req.payload.db.updateOne({
266
+ collection: LINKS,
267
+ id: link.id,
268
+ data: { destination: next },
269
+ returning: false,
270
+ req,
271
+ });
268
272
  }
269
273
  return failed;
270
274
  };
@@ -293,7 +297,11 @@ export const followDestination = (resolved, collection) => async ({ doc, operati
293
297
  const next = destinationOf(collection, stored);
294
298
  const moving = links.filter((link) => link.key && link.destination !== next);
295
299
  const failed = await moveLinks(req, resolved, next, moving);
296
- if (failed.length > 0)
300
+ // Throwing undoes this save, and in a transaction it also undoes the stored copies of the moves the service
301
+ // took. Those links would then open an address that no copy here holds, and the sync, which compares the
302
+ // copies with the document, would not find them. So the save is refused only when the service moved nothing.
303
+ // Otherwise it stands, and the next save or sync moves the rest.
304
+ if (failed.length > 0 && failed.length === moving.length)
297
305
  throw new APIError(`${failed.length} of ${moving.length} tracked links to this still open the old address (${failed[0]}). Save again to retry; the next sync also retries.`, 502);
298
306
  return doc;
299
307
  };
@@ -13,6 +13,8 @@ export type Resolved = {
13
13
  disabled: boolean;
14
14
  /** Whether the request's user manages every link. Takes a real request, or `{ user }` where only that is known. */
15
15
  manages: (req: Pick<PayloadRequest, 'user'>) => boolean;
16
+ /** The host's rules for the links collection, which replace the plugin's. */
17
+ access: NonNullable<CardwareLinkOptions['access']>['collection'];
16
18
  group?: string;
17
19
  prefix: string;
18
20
  collections: ResolvedCollection[];
@@ -42,6 +42,7 @@ export const resolve = (options) => {
42
42
  return {
43
43
  disabled: Boolean(options.disabled),
44
44
  manages: (req) => Boolean(req.user) && manage({ req: req }),
45
+ access: options.access?.collection,
45
46
  group: options.admin?.group,
46
47
  prefix,
47
48
  collections,
@@ -41,6 +41,11 @@ export type CardwareLinkOptions = {
41
41
  manage?: (args: {
42
42
  req: PayloadRequest;
43
43
  }) => boolean;
44
+ /**
45
+ * The `tracked-links` collection's rules, operation by operation, in place of the plugin's own, for a host that
46
+ * keeps every rule in one table. Making a link still checks that the user may link to its target.
47
+ */
48
+ collection?: Partial<Record<'create' | 'read' | 'update' | 'delete', Access>>;
44
49
  };
45
50
  admin?: {
46
51
  /** Admin navigation group for the links collection. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cardware/cardware-link",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "The client for cardware.link, CardWare's link-tracking service, and its Payload plugin.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -11,15 +11,16 @@
11
11
  },
12
12
  "homepage": "https://github.com/cardware/cardware-link/tree/main/packages/cardware-link#readme",
13
13
  "publishConfig": {
14
- "access": "public",
15
- "provenance": true
14
+ "access": "public"
16
15
  },
17
16
  "files": [
18
17
  "dist",
19
18
  "src/client",
20
19
  "README.md"
21
20
  ],
22
- "sideEffects": false,
21
+ "sideEffects": [
22
+ "*.css"
23
+ ],
23
24
  "exports": {
24
25
  ".": {
25
26
  "bun": "./src/client/index.ts",
@@ -41,14 +42,18 @@
41
42
  "./package.json": "./package.json"
42
43
  },
43
44
  "scripts": {
44
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
45
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/payload/admin/*.css dist/payload/admin/",
45
46
  "prepublishOnly": "bun run build"
46
47
  },
47
48
  "peerDependencies": {
49
+ "@payloadcms/ui": "^4.0.0-beta.9",
48
50
  "payload": "^4.0.0-beta.9",
49
51
  "react": "^19"
50
52
  },
51
53
  "peerDependenciesMeta": {
54
+ "@payloadcms/ui": {
55
+ "optional": true
56
+ },
52
57
  "payload": {
53
58
  "optional": true
54
59
  },
@@ -58,6 +63,7 @@
58
63
  },
59
64
  "devDependencies": {
60
65
  "@payloadcms/db-mongodb": "4.0.0-beta.9",
66
+ "@payloadcms/ui": "4.0.0-beta.9",
61
67
  "@types/react": "19.2.14",
62
68
  "payload": "4.0.0-beta.9",
63
69
  "react": "19.2.4"