@cardware/cardware-link 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cardware Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,115 @@
1
- # Temporary Holding Version
1
+ # @cardware/cardware-link
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
+ The client for [cardware.link](https://github.com/cardware/cardware-link), CardWare's link-tracking service, and
4
+ its Payload plugin.
5
+
6
+ ```sh
7
+ npm install @cardware/cardware-link
8
+ ```
9
+
10
+ | Import | What |
11
+ | ---------------------------------------- | ------------------------------------------------------------------------- |
12
+ | `@cardware/cardware-link` | The v1 API client, key rules and types. No dependencies. |
13
+ | `@cardware/cardware-link/payload` | The Payload plugin (Payload 4). |
14
+ | `@cardware/cardware-link/payload/admin` | The plugin's admin component, loaded through Payload's import map. |
15
+ | `@cardware/cardware-link/payload/client` | The browser helper that reports saves from a page a link opened. No deps. |
16
+
17
+ `payload` and `react` are optional peer dependencies, needed only for the plugin; a client-only install pulls in
18
+ nothing else.
19
+
20
+ ## The client
21
+
22
+ ```ts
23
+ import { createLinkClient } from '@cardware/cardware-link'
24
+
25
+ const links = createLinkClient({ baseURL: 'https://cardware.link', key: process.env.LINK_SERVICE_KEY! })
26
+ const { key, url } = await links.create({
27
+ prefix: 'c',
28
+ destination: 'https://cardware.com/dir/ada-lovelace/abc123',
29
+ })
30
+ const { totals } = await links.get(key)
31
+ ```
32
+
33
+ The client runs anywhere `fetch` does. It also exports the key rules (`isKey`, `newKey`, `isPrefix`) and the API's
34
+ types. Every method, and the API it calls, is described in the
35
+ [repository's README](https://github.com/cardware/cardware-link#use-the-api).
36
+
37
+ ## The Payload plugin
38
+
39
+ ```ts
40
+ // payload.config.ts → plugins
41
+ import { cardwareLinkPlugin } from '@cardware/cardware-link/payload'
42
+
43
+ cardwareLinkPlugin({
44
+ access: { manage: ({ req }) => Boolean(req.user?.roles?.includes('admin')) },
45
+ admin: { group: 'CardWare' },
46
+ collections: {
47
+ employees: {
48
+ // Who may link to which documents, as Payload access: true, false or a query. Managers always may.
49
+ access: { links: ({ req }) => (req.user ? { user: { equals: req.user.id } } : false) },
50
+ tracking: {
51
+ // The URL a link to this document opens. Links follow it when the document changes.
52
+ destination: (employee) =>
53
+ `https://cardware.com/dir/${employee.firstName}-${employee.lastName}/${employee.publicHash}`,
54
+ code: { logo: true }, // the CardWare mark in the middle of the code; default true
55
+ },
56
+ },
57
+ },
58
+ tracking: {
59
+ service: { url: process.env.LINK_SERVICE_URL, key: process.env.LINK_SERVICE_KEY },
60
+ prefix: 'c', // default
61
+ sync: { cron: '*/10 * * * *' }, // default; `false` turns the schedule off
62
+ callerAddress: (headers) => headers.get('x-real-ip') ?? 'unknown', // forwarded with saves, never stored
63
+ },
64
+ })
65
+ ```
66
+
67
+ Payload's own keys sit at the top level (`disabled`, `access.manage`, `admin.group`, `collections`); the plugin's
68
+ settings sit under `tracking`, globally and per collection.
69
+
70
+ What it adds:
71
+
72
+ - **A `tracked-links` collection:** label, a polymorphic `target`, and the `key`, `url` and `destination` the service
73
+ answered, plus `retired` and the copied counts `scans`, `uniqueScanners`, `saves` and `syncedAt`.
74
+ - Creating a link calls `POST /v1/links` with `externalRef` `<collection>:<id>` and an `Idempotency-Key`; a lost
75
+ answer is retried once with the same key. If the service can't be reached, the create fails with a clear
76
+ message and nothing is stored.
77
+ - The target, key, URL and destination are fixed once the link is made. Changes to `label` and `retired` are sent
78
+ with `PATCH` first, and a refusal stops the save.
79
+ - Only managers delete a link, and deleting it retires it on the service.
80
+ - **On each tracked collection:** a `trackedLinks` join field listing the document's links; an `afterRead` hook that
81
+ drops it when there is no signed-in user, so pages that read documents on the server never hand links to the
82
+ public; a `beforeDelete` hook that refuses to delete a document with links; and an `afterChange` hook that sends a
83
+ new destination with `PATCH` to every link whose stored destination no longer matches, so printed codes follow the
84
+ document. A failed move is reported, and the next save retries it.
85
+ - **A scheduled job,** `cardware-link-sync` on queue `cardware-link`, every 10 minutes: copies totals through
86
+ `POST /v1/links/totals`, 100 links a call, so admin lists sort and filter by counts. `syncLinkTotals(payload)` runs
87
+ it on demand. Payload runs scheduled jobs only where crons are on: call `getPayload({ config, cron: true })` once on
88
+ the server, for example from Next's `instrumentation.ts`.
89
+ - **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.
91
+ - **Endpoints:**
92
+ - `GET /api/tracked-links/:id/code?format=svg|png&size=&mm=&dpi=&download=1`, for users who may read the link: the
93
+ service's code, fetched with the app key, so the key never reaches the browser.
94
+ - `POST /api/tracked-links/save` with `{ key }`, public: forwards a save to `POST /v1/links/:key/events` with the
95
+ phone's `user-agent`, `sec-purpose` and `purpose` and the caller's address, and answers with the service's status
96
+ (201 counted, 202 not counted, 400 or 404 refused).
97
+
98
+ `disabled: true` keeps the collection and fields, so the schema doesn't change, and stops talking to the service.
99
+ Without `tracking.service.url` and `key`, Payload still starts (with a warning) and making a link fails with a clear
100
+ message.
101
+
102
+ ### Reporting saves from the page a link opens
103
+
104
+ The service sends a scan on to the destination with `?l=<key>` added. On that page:
105
+
106
+ ```ts
107
+ 'use client'
108
+ import { reportLinkSave, takeLinkKey } from '@cardware/cardware-link/payload/client'
109
+
110
+ const key = takeLinkKey() // reads ?l=, removes it from the address bar with history.replaceState
111
+ // …when the visitor saves the contact file:
112
+ if (key) void reportLinkSave(key) // POST /api/tracked-links/save, keepalive; never throws
113
+ ```
114
+
115
+ Without `?l=`, `takeLinkKey` changes nothing and returns `undefined`.
@@ -0,0 +1,46 @@
1
+ import type { CodeOptions, CreatedLink, CreateLinkInput, EventResult, ForwardedRequest, Link, LinkDay, LinkPage, LinkPatch, LinkTotals } from './types.ts';
2
+ export type LinkClientOptions = {
3
+ /** The service's origin, such as `https://cardware.link`. */
4
+ baseURL: string;
5
+ /** The app's key, `cwl_live_…`. */
6
+ key: string;
7
+ fetch?: typeof fetch;
8
+ };
9
+ /** A refusal from the service: its status and its `error` message. */
10
+ export declare class LinkServiceError extends Error {
11
+ readonly status: number;
12
+ readonly body: unknown;
13
+ constructor(status: number, body: unknown);
14
+ }
15
+ export declare const createLinkClient: ({ baseURL, key, fetch: fetcher }: LinkClientOptions) => {
16
+ /** Makes a link. With `idempotencyKey`, a retried create returns the first link instead of a second one. */
17
+ create: (input: CreateLinkInput, { idempotencyKey }?: {
18
+ idempotencyKey?: string;
19
+ }) => Promise<CreatedLink>;
20
+ get: (linkKey: string) => Promise<Link>;
21
+ list: (params?: {
22
+ externalRef?: string;
23
+ prefix?: string;
24
+ cursor?: string;
25
+ limit?: number;
26
+ }) => Promise<LinkPage>;
27
+ /** Totals for up to 100 links; links the app doesn't own are left out. */
28
+ totals: (keys: string[]) => Promise<Record<string, LinkTotals>>;
29
+ days: (linkKey: string, range?: {
30
+ from?: string;
31
+ to?: string;
32
+ }) => Promise<LinkDay[]>;
33
+ /** Changes the label, the destination or whether the link is retired. The key and URL never change. */
34
+ update: (linkKey: string, patch: LinkPatch) => Promise<Link>;
35
+ /** Reports a save, forwarding what the phone sent. */
36
+ reportSave: (linkKey: string, request: ForwardedRequest) => Promise<EventResult>;
37
+ /** The full URL of a link's code. Fetching it needs the app's key; `code` does that. */
38
+ codeURL: (linkKey: string, options?: CodeOptions) => string;
39
+ /** A link's code, as SVG text or PNG bytes, with its ETag. */
40
+ code: (linkKey: string, options?: CodeOptions) => Promise<{
41
+ body: Uint8Array<ArrayBuffer>;
42
+ contentType: string;
43
+ etag: string | null;
44
+ }>;
45
+ };
46
+ export type LinkClient = ReturnType<typeof createLinkClient>;
@@ -0,0 +1,84 @@
1
+ /** A refusal from the service: its status and its `error` message. */
2
+ export class LinkServiceError extends Error {
3
+ status;
4
+ body;
5
+ constructor(status, body) {
6
+ const message = body && typeof body === 'object' && 'error' in body ? String(body.error) : `status ${status}`;
7
+ super(`cardware.link: ${message}`);
8
+ this.status = status;
9
+ this.body = body;
10
+ this.name = 'LinkServiceError';
11
+ }
12
+ }
13
+ const query = (params) => {
14
+ const search = new URLSearchParams();
15
+ for (const [name, value] of Object.entries(params))
16
+ if (value !== undefined)
17
+ search.set(name, String(value));
18
+ const text = search.toString();
19
+ return text ? `?${text}` : '';
20
+ };
21
+ export const createLinkClient = ({ baseURL, key, fetch: fetcher = fetch }) => {
22
+ const origin = baseURL.replace(/\/+$/, '');
23
+ const call = async (path, init = {}) => {
24
+ const response = await fetcher(`${origin}${path}`, {
25
+ ...init,
26
+ headers: {
27
+ authorization: `Bearer ${key}`,
28
+ ...(init.body ? { 'content-type': 'application/json' } : {}),
29
+ ...init.headers,
30
+ },
31
+ });
32
+ const body = response.status === 204 ? undefined : await response.json().catch(() => undefined);
33
+ if (!response.ok)
34
+ throw new LinkServiceError(response.status, body);
35
+ return body;
36
+ };
37
+ const linkPath = (linkKey) => `/v1/links/${encodeURIComponent(linkKey)}`;
38
+ /** The path of a link's code on the service, with its options. */
39
+ const codePath = (linkKey, options = {}) => {
40
+ const { format = 'svg', ...rest } = options;
41
+ return `${linkPath(linkKey)}/code.${format}${query({
42
+ ...rest,
43
+ logo: rest.logo === false ? 0 : undefined,
44
+ })}`;
45
+ };
46
+ return {
47
+ /** Makes a link. With `idempotencyKey`, a retried create returns the first link instead of a second one. */
48
+ create: (input, { idempotencyKey } = {}) => call('/v1/links', {
49
+ method: 'POST',
50
+ body: JSON.stringify(input),
51
+ headers: idempotencyKey ? { 'idempotency-key': idempotencyKey } : {},
52
+ }),
53
+ get: (linkKey) => call(linkPath(linkKey)),
54
+ list: (params = {}) => call(`/v1/links${query(params)}`),
55
+ /** Totals for up to 100 links; links the app doesn't own are left out. */
56
+ totals: (keys) => call('/v1/links/totals', {
57
+ method: 'POST',
58
+ body: JSON.stringify({ keys }),
59
+ }).then(({ totals }) => totals),
60
+ days: (linkKey, range = {}) => call(`${linkPath(linkKey)}/days${query(range)}`).then(({ days }) => days),
61
+ /** Changes the label, the destination or whether the link is retired. The key and URL never change. */
62
+ update: (linkKey, patch) => call(linkPath(linkKey), { method: 'PATCH', body: JSON.stringify(patch) }),
63
+ /** Reports a save, forwarding what the phone sent. */
64
+ reportSave: (linkKey, request) => call(`${linkPath(linkKey)}/events`, {
65
+ method: 'POST',
66
+ body: JSON.stringify({ kind: 'save', request }),
67
+ }),
68
+ /** The full URL of a link's code. Fetching it needs the app's key; `code` does that. */
69
+ codeURL: (linkKey, options) => `${origin}${codePath(linkKey, options)}`,
70
+ /** A link's code, as SVG text or PNG bytes, with its ETag. */
71
+ code: async (linkKey, options = {}) => {
72
+ const response = await fetcher(`${origin}${codePath(linkKey, options)}`, {
73
+ headers: { authorization: `Bearer ${key}` },
74
+ });
75
+ if (!response.ok)
76
+ throw new LinkServiceError(response.status, await response.json().catch(() => undefined));
77
+ return {
78
+ body: new Uint8Array(await response.arrayBuffer()),
79
+ contentType: response.headers.get('content-type') ?? '',
80
+ etag: response.headers.get('etag'),
81
+ };
82
+ },
83
+ };
84
+ };
@@ -0,0 +1,3 @@
1
+ export { createLinkClient, type LinkClient, type LinkClientOptions, LinkServiceError } from './client.ts';
2
+ export * from './key.ts';
3
+ export type * from './types.ts';
@@ -0,0 +1,2 @@
1
+ export { createLinkClient, LinkServiceError } from './client.js';
2
+ export * from './key.js';
@@ -0,0 +1,13 @@
1
+ /** Crockford base32 in lower case: no `i`, `l`, `o` or `u`, so a key read aloud or retyped survives. */
2
+ export declare const KEY_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
3
+ /**
4
+ * Ten characters, 50 bits: too many to guess, and short enough that `https://cardware.link/c/<key>` stays a version 4
5
+ * code at error correction H. Printed codes carry the key for good, so any key of an allowed length keeps opening.
6
+ */
7
+ export declare const DEFAULT_KEY_LENGTH = 10;
8
+ export declare const MIN_KEY_LENGTH = 8;
9
+ export declare const MAX_KEY_LENGTH = 32;
10
+ /** A prefix is one lower-case letter: `c` for cards, and one each for other apps. */
11
+ export declare const isPrefix: (value: string) => boolean;
12
+ export declare const newKey: (length?: number) => string;
13
+ export declare const isKey: (value: string) => boolean;
@@ -0,0 +1,15 @@
1
+ /** Crockford base32 in lower case: no `i`, `l`, `o` or `u`, so a key read aloud or retyped survives. */
2
+ export const KEY_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
3
+ /**
4
+ * Ten characters, 50 bits: too many to guess, and short enough that `https://cardware.link/c/<key>` stays a version 4
5
+ * code at error correction H. Printed codes carry the key for good, so any key of an allowed length keeps opening.
6
+ */
7
+ export const DEFAULT_KEY_LENGTH = 10;
8
+ export const MIN_KEY_LENGTH = 8;
9
+ export const MAX_KEY_LENGTH = 32;
10
+ /** A prefix is one lower-case letter: `c` for cards, and one each for other apps. */
11
+ export const isPrefix = (value) => /^[a-z]$/.test(value);
12
+ export const newKey = (length = DEFAULT_KEY_LENGTH) => Array.from(crypto.getRandomValues(new Uint8Array(length)), (byte) => KEY_ALPHABET[byte & 31]).join('');
13
+ export const isKey = (value) => value.length >= MIN_KEY_LENGTH &&
14
+ value.length <= MAX_KEY_LENGTH &&
15
+ [...value].every((char) => KEY_ALPHABET.includes(char));
@@ -0,0 +1,69 @@
1
+ export type Device = 'ios' | 'android' | 'other';
2
+ export type EventKind = 'scan' | 'save';
3
+ /** A link's three counts. Unique scanners are scans from a browser that had not opened the link before. */
4
+ export type LinkTotals = {
5
+ scans: number;
6
+ uniqueScanners: number;
7
+ saves: number;
8
+ };
9
+ export type Link = {
10
+ key: string;
11
+ prefix: string;
12
+ url: string;
13
+ destination: string;
14
+ label: string | null;
15
+ externalRef: string | null;
16
+ metadata: Record<string, unknown>;
17
+ retired: boolean;
18
+ createdAt: string;
19
+ totals: LinkTotals;
20
+ };
21
+ export type CreatedLink = Pick<Link, 'key' | 'url' | 'destination' | 'createdAt'>;
22
+ export type CreateLinkInput = {
23
+ prefix: string;
24
+ destination: string;
25
+ label?: string;
26
+ externalRef?: string;
27
+ metadata?: Record<string, unknown>;
28
+ };
29
+ export type LinkPatch = {
30
+ label?: string | null;
31
+ retired?: boolean;
32
+ destination?: string;
33
+ };
34
+ export type LinkPage = {
35
+ links: Link[];
36
+ nextCursor: string | null;
37
+ };
38
+ export type LinkDay = {
39
+ day: string;
40
+ } & LinkTotals;
41
+ /**
42
+ * What the phone sent with a request, forwarded by the app so the service judges a save as it judges a scan. The
43
+ * address is used for the rate limit and never stored.
44
+ */
45
+ export type ForwardedRequest = {
46
+ userAgent: string;
47
+ secPurpose?: string;
48
+ purpose?: string;
49
+ address: string;
50
+ };
51
+ export type NotCounted = 'retired' | 'program' | 'over-limit';
52
+ export type EventResult = {
53
+ counted: true;
54
+ } | {
55
+ counted: false;
56
+ reason: NotCounted;
57
+ };
58
+ export type CodeOptions = {
59
+ format?: 'svg';
60
+ size?: number;
61
+ mm?: number;
62
+ logo?: boolean;
63
+ } | {
64
+ format: 'png';
65
+ size?: number;
66
+ mm?: number;
67
+ dpi?: number;
68
+ logo?: boolean;
69
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { PayloadRequest, Where } from 'payload';
2
+ import type { Resolved, ResolvedCollection } from './options.ts';
3
+ type Linkable = {
4
+ relationTo: ResolvedCollection['slug'];
5
+ ids: (number | string)[] | 'all';
6
+ };
7
+ /** The documents of each collection the signed-in user may link to. Managers aren't asked: they may link to any. */
8
+ export declare const linkableTargets: (req: PayloadRequest, resolved: Resolved) => Promise<Linkable[]>;
9
+ /** Whether the signed-in user may make a link to this document. */
10
+ export declare const mayLinkTo: (req: PayloadRequest, resolved: Resolved, relationTo: string, id: number | string) => Promise<boolean>;
11
+ /** Links a user may see and edit: every link for a manager, otherwise the links to documents they may link to. */
12
+ export declare const linksWhere: (req: PayloadRequest, resolved: Resolved) => Promise<boolean | Where>;
13
+ export {};
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Answers worked out once per request. Payload asks access for the list, each join and each field, and the answers
3
+ * can't change within one request. Keyed by the request's data loader, made once per request: Payload hands each
4
+ * access function its own view of the request, so `req` itself is a new object each time.
5
+ */
6
+ const perRequest = (compute) => {
7
+ const cache = new WeakMap();
8
+ return (req, resolved) => {
9
+ const key = req.payloadDataLoader ?? req;
10
+ let found = cache.get(key);
11
+ if (!found) {
12
+ found = compute(req, resolved);
13
+ cache.set(key, found);
14
+ }
15
+ return found;
16
+ };
17
+ };
18
+ /** The documents of each collection the signed-in user may link to. Managers aren't asked: they may link to any. */
19
+ export const linkableTargets = perRequest(async (req, resolved) => {
20
+ if (!req.user)
21
+ return [];
22
+ return Promise.all(resolved.collections.map(async (collection) => {
23
+ const where = await collection.linkable(req);
24
+ if (where === true)
25
+ return { relationTo: collection.slug, ids: 'all' };
26
+ if (!where)
27
+ return { relationTo: collection.slug, ids: [] };
28
+ const found = await req.payload.find({
29
+ collection: collection.slug,
30
+ where,
31
+ depth: 0,
32
+ pagination: false,
33
+ select: {},
34
+ overrideAccess: true,
35
+ req,
36
+ });
37
+ return { relationTo: collection.slug, ids: found.docs.map((doc) => doc.id) };
38
+ }));
39
+ });
40
+ const sameId = (a, b) => String(a) === String(b);
41
+ /** Whether the signed-in user may make a link to this document. */
42
+ export const mayLinkTo = async (req, resolved, relationTo, id) => {
43
+ if (resolved.manages(req))
44
+ return true;
45
+ const linkable = (await linkableTargets(req, resolved)).find((entry) => entry.relationTo === relationTo);
46
+ return linkable?.ids === 'all' || Boolean(linkable?.ids.some((each) => sameId(each, id)));
47
+ };
48
+ /** Links a user may see and edit: every link for a manager, otherwise the links to documents they may link to. */
49
+ export const linksWhere = async (req, resolved) => {
50
+ if (!req.user)
51
+ return false;
52
+ if (resolved.manages(req))
53
+ return true;
54
+ const linkable = (await linkableTargets(req, resolved)).filter(({ ids }) => ids.length > 0);
55
+ if (linkable.length === 0)
56
+ return false;
57
+ return {
58
+ or: linkable.map(({ relationTo, ids }) => ({
59
+ and: [
60
+ { 'target.relationTo': { equals: relationTo } },
61
+ ...(ids === 'all' ? [] : [{ 'target.value': { in: ids } }]),
62
+ ],
63
+ })),
64
+ };
65
+ };
@@ -0,0 +1 @@
1
+ export { LinkPanel } from './link-panel.tsx';
@@ -0,0 +1 @@
1
+ export { LinkPanel } from './link-panel.js';
@@ -0,0 +1,7 @@
1
+ import type { UIFieldServerProps } from 'payload';
2
+ /**
3
+ * The link's code, its URL, its live totals and downloads of the code. Rendered on the server: the totals are read
4
+ * from the service here, and the code is an image from the plugin's code endpoint, so the app key never reaches the
5
+ * browser. Nothing shows until the link is saved and has its key.
6
+ */
7
+ export declare function LinkPanel({ data, payload }: UIFieldServerProps): Promise<import("react/jsx-runtime").JSX.Element | null>;
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { resolvedOf } from '../options.js';
3
+ import { LINKS } from '../types.js';
4
+ /** A thermal label printer's resolution. */
5
+ const LABEL_DPI = 203;
6
+ const button = 'btn btn--style-secondary btn--size-small btn--icon-style-without-border';
7
+ /**
8
+ * The link's code, its URL, its live totals and downloads of the code. Rendered on the server: the totals are read
9
+ * from the service here, and the code is an image from the plugin's code endpoint, so the app key never reaches the
10
+ * browser. Nothing shows until the link is saved and has its key.
11
+ */
12
+ export async function LinkPanel({ data, payload }) {
13
+ if (!data?.id || !data.key || !data.url)
14
+ return null;
15
+ const key = String(data.key);
16
+ const url = String(data.url);
17
+ const resolved = resolvedOf(payload);
18
+ let live;
19
+ let problem;
20
+ try {
21
+ if (!resolved)
22
+ throw new Error('cardware.link is not installed.');
23
+ live = await resolved.service('Live totals unavailable', (client) => client.get(key));
24
+ }
25
+ catch (error) {
26
+ problem = error instanceof Error ? error.message : String(error);
27
+ }
28
+ const totals = live?.totals ?? {
29
+ scans: Number(data.scans ?? 0),
30
+ uniqueScanners: Number(data.uniqueScanners ?? 0),
31
+ saves: Number(data.saves ?? 0),
32
+ };
33
+ const code = `${payload.config.routes.api}/${LINKS}/${data.id}/code`;
34
+ const stats = [
35
+ ['Scans', totals.scans],
36
+ ['Unique scanners', totals.uniqueScanners],
37
+ ['Saves', totals.saves],
38
+ ];
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"] })] })] })] }));
40
+ }
@@ -0,0 +1,17 @@
1
+ /** The plugin's save endpoint on the site, under Payload's default `/api` route. */
2
+ export declare const SAVE_ENDPOINT = "/api/tracked-links/save";
3
+ /**
4
+ * The key of the link that opened this page, from `?<param>=<key>` (default `l`), removed from the address bar with
5
+ * `history.replaceState` the first time it is read. Later calls on the same page answer the same key, so a component
6
+ * that mounts twice still finds it. Undefined without one, or for a value that isn't a key.
7
+ */
8
+ export declare const takeLinkKey: ({ param }?: {
9
+ param?: string;
10
+ }) => string | undefined;
11
+ /**
12
+ * Reports a save of what the link opened. Sent with `keepalive`, so it survives the page going away. Never throws:
13
+ * a failed report must never stand between the visitor and the file. Answers whether the service counted it.
14
+ */
15
+ export declare const reportLinkSave: (key: string, { endpoint }?: {
16
+ endpoint?: string;
17
+ }) => Promise<boolean>;
@@ -0,0 +1,44 @@
1
+ // The browser's half of reporting saves. A page a link opened reads the link's key from `?l=<key>`, takes it out
2
+ // of the address bar, and reports a save to the site's endpoint when the visitor keeps what the page offers. Runs in
3
+ // the browser only; imports nothing but the key rules.
4
+ import { isKey } from '../client/key.js';
5
+ /** The plugin's save endpoint on the site, under Payload's default `/api` route. */
6
+ export const SAVE_ENDPOINT = '/api/tracked-links/save';
7
+ let taken;
8
+ /**
9
+ * The key of the link that opened this page, from `?<param>=<key>` (default `l`), removed from the address bar with
10
+ * `history.replaceState` the first time it is read. Later calls on the same page answer the same key, so a component
11
+ * that mounts twice still finds it. Undefined without one, or for a value that isn't a key.
12
+ */
13
+ export const takeLinkKey = ({ param = 'l' } = {}) => {
14
+ if (typeof window === 'undefined')
15
+ return undefined;
16
+ const url = new URL(window.location.href);
17
+ const value = url.searchParams.get(param);
18
+ if (value === null)
19
+ return taken?.path === url.pathname ? taken.key : undefined;
20
+ url.searchParams.delete(param);
21
+ window.history.replaceState(window.history.state, '', url);
22
+ taken = { path: url.pathname, key: isKey(value) ? value : undefined };
23
+ return taken.key;
24
+ };
25
+ /**
26
+ * Reports a save of what the link opened. Sent with `keepalive`, so it survives the page going away. Never throws:
27
+ * a failed report must never stand between the visitor and the file. Answers whether the service counted it.
28
+ */
29
+ export const reportLinkSave = async (key, { endpoint = SAVE_ENDPOINT } = {}) => {
30
+ if (!isKey(key))
31
+ return false;
32
+ try {
33
+ const response = await fetch(endpoint, {
34
+ method: 'POST',
35
+ headers: { 'content-type': 'application/json' },
36
+ body: JSON.stringify({ key }),
37
+ keepalive: true,
38
+ });
39
+ return response.status === 201;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ };
@@ -0,0 +1,38 @@
1
+ import { type CollectionAfterChangeHook, type CollectionAfterReadHook, type CollectionConfig, type CollectionSlug, type JoinField, type PayloadRequest } from 'payload';
2
+ import { type Resolved, type ResolvedCollection } from './options.ts';
3
+ import { type StoredLink } from './types.ts';
4
+ /** Where the admin finds the link's panel: the package's own admin entry, which the host's import map loads. */
5
+ export declare const LINK_PANEL = "@cardware/cardware-link/payload/admin#LinkPanel";
6
+ /**
7
+ * The whole target document, as stored: re-read with access overridden, hidden fields shown and no `select`, so the
8
+ * destination never comes from a trimmed copy such as the one a hook receives.
9
+ */
10
+ export declare const targetDoc: (req: Pick<PayloadRequest, 'payload'> & Partial<PayloadRequest>, slug: CollectionSlug, id: number | string) => Promise<(import("payload").JsonObject & import("payload").TypeWithID) | null>;
11
+ export declare const destinationOf: (collection: ResolvedCollection, doc: object) => string;
12
+ export declare const linksCollection: (resolved: Resolved) => CollectionConfig;
13
+ /** A target with links can't be deleted: printed codes would lose what they open. A manager deletes the links first. */
14
+ export declare const refuseDeleteWhileLinked: (relationTo: CollectionSlug) => ({ id, req }: {
15
+ id: number | string;
16
+ req: PayloadRequest;
17
+ }) => Promise<void>;
18
+ /**
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.
21
+ */
22
+ export declare const moveLinks: (req: Pick<PayloadRequest, 'payload'> & Partial<PayloadRequest>, resolved: Resolved, next: string, links: Pick<StoredLink, 'id' | 'key' | 'destination'>[]) => Promise<string[]>;
23
+ /**
24
+ * Moves every link to a document whose destination no longer matches the document. Compares with each link's own
25
+ * copy of its destination, not the previous document, so a save after a failed move tries again (and so does the
26
+ * sync job). Reads the document again in full: the one a hook receives may be trimmed by the caller's `select`.
27
+ */
28
+ export declare const followDestination: (resolved: Resolved, collection: ResolvedCollection) => CollectionAfterChangeHook;
29
+ /**
30
+ * The links to a document, on the document's own screen, where a new one can be made with the target filled in.
31
+ * Only a signed-in reader gets them: see `withoutLinksForThePublic`.
32
+ */
33
+ export declare const linksJoinField: () => JoinField;
34
+ /**
35
+ * Pages that render a document for the public read it on the server with no user, often with access overridden,
36
+ * and may hand the whole record to the browser. Without a user, a document comes back without its links.
37
+ */
38
+ export declare const withoutLinksForThePublic: CollectionAfterReadHook;