@cardware/cardware-link 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +121 -2
- package/dist/client/client.d.ts +46 -0
- package/dist/client/client.js +84 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +2 -0
- package/dist/client/key.d.ts +13 -0
- package/dist/client/key.js +15 -0
- package/dist/client/types.d.ts +69 -0
- package/dist/client/types.js +1 -0
- package/dist/payload/access.d.ts +13 -0
- package/dist/payload/access.js +65 -0
- package/dist/payload/admin/index.d.ts +1 -0
- package/dist/payload/admin/index.js +1 -0
- package/dist/payload/admin/link-panel.css +80 -0
- package/dist/payload/admin/link-panel.d.ts +8 -0
- package/dist/payload/admin/link-panel.js +47 -0
- package/dist/payload/client.d.ts +17 -0
- package/dist/payload/client.js +44 -0
- package/dist/payload/collections.d.ts +38 -0
- package/dist/payload/collections.js +325 -0
- package/dist/payload/endpoints.d.ts +3 -0
- package/dist/payload/endpoints.js +113 -0
- package/dist/payload/index.d.ts +11 -0
- package/dist/payload/index.js +49 -0
- package/dist/payload/options.d.ts +46 -0
- package/dist/payload/options.js +80 -0
- package/dist/payload/sync.d.ts +18 -0
- package/dist/payload/sync.js +126 -0
- package/dist/payload/types.d.ts +107 -0
- package/dist/payload/types.js +7 -0
- package/package.json +70 -5
- package/src/client/client.ts +114 -0
- package/src/client/index.ts +3 -0
- package/src/client/key.ts +21 -0
- package/src/client/types.ts +54 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { APIError } from 'payload';
|
|
2
|
+
import { createLinkClient, LinkServiceError } from '../client/client.js';
|
|
3
|
+
import { isPrefix } from '../client/key.js';
|
|
4
|
+
import { SYNC_QUEUE } from './types.js';
|
|
5
|
+
const defaultCallerAddress = (headers) => headers.get('x-real-ip')?.trim() || 'unknown';
|
|
6
|
+
/** Why a call to the service failed, in words for the person who asked for it. */
|
|
7
|
+
export const serviceFailure = (what, error) => {
|
|
8
|
+
if (error instanceof APIError)
|
|
9
|
+
return error;
|
|
10
|
+
if (error instanceof LinkServiceError) {
|
|
11
|
+
const status = error.status >= 400 && error.status < 500 ? error.status : 502;
|
|
12
|
+
return new APIError(`${what}: ${error.message}`, status);
|
|
13
|
+
}
|
|
14
|
+
return new APIError(`${what}: cardware.link could not be reached. Try again in a moment.`, 503);
|
|
15
|
+
};
|
|
16
|
+
const resolveCollection = (slug, settings) => {
|
|
17
|
+
if (typeof settings?.tracking?.destination !== 'function')
|
|
18
|
+
throw new Error(`cardware.link: collections.${slug}.tracking.destination must be a function.`);
|
|
19
|
+
const links = settings.access?.links;
|
|
20
|
+
return {
|
|
21
|
+
slug,
|
|
22
|
+
linkable: async (req) => (req.user && links ? links({ req, slug }) : false),
|
|
23
|
+
destination: settings.tracking.destination,
|
|
24
|
+
logo: settings.tracking.code?.logo ?? true,
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
export const resolve = (options) => {
|
|
28
|
+
const { tracking } = options;
|
|
29
|
+
const manage = options.access?.manage ?? (({ req }) => Boolean(req.user));
|
|
30
|
+
const prefix = tracking.prefix ?? 'c';
|
|
31
|
+
if (!isPrefix(prefix))
|
|
32
|
+
throw new Error('cardware.link: tracking.prefix must be one lower-case letter.');
|
|
33
|
+
const collections = Object.keys(options.collections).flatMap((slug) => {
|
|
34
|
+
const settings = options.collections[slug];
|
|
35
|
+
return settings ? [resolveCollection(slug, settings)] : [];
|
|
36
|
+
});
|
|
37
|
+
if (collections.length === 0)
|
|
38
|
+
throw new Error('cardware.link: name at least one collection.');
|
|
39
|
+
const { url, key } = tracking.service ?? {};
|
|
40
|
+
const client = url && key ? createLinkClient({ baseURL: url, key }) : undefined;
|
|
41
|
+
const sync = tracking.sync === false ? undefined : (tracking.sync ?? {});
|
|
42
|
+
return {
|
|
43
|
+
disabled: Boolean(options.disabled),
|
|
44
|
+
manages: (req) => Boolean(req.user) && manage({ req: req }),
|
|
45
|
+
access: options.access?.collection,
|
|
46
|
+
group: options.admin?.group,
|
|
47
|
+
prefix,
|
|
48
|
+
collections,
|
|
49
|
+
configured: Boolean(client),
|
|
50
|
+
service: async (what, call) => {
|
|
51
|
+
if (options.disabled)
|
|
52
|
+
throw new APIError(`${what}: cardware.link is turned off on this site.`, 503);
|
|
53
|
+
if (!client)
|
|
54
|
+
throw new APIError(`${what}: cardware.link is not set up on this site (tracking.service needs a URL and a key).`, 503);
|
|
55
|
+
try {
|
|
56
|
+
return await call(client);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
throw serviceFailure(what, error);
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
callerAddress: tracking.callerAddress ?? defaultCallerAddress,
|
|
63
|
+
sync: sync && {
|
|
64
|
+
cron: sync.cron ?? '*/10 * * * *',
|
|
65
|
+
queue: sync.queue ?? SYNC_QUEUE,
|
|
66
|
+
autoRun: sync.autoRun ?? true,
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
export const collectionOf = (resolved, slug) => resolved.collections.find((collection) => collection.slug === slug);
|
|
71
|
+
const KEY = 'cardwareLink';
|
|
72
|
+
/**
|
|
73
|
+
* The resolved options, kept on the server-only `config.custom` so the admin panel reads the same settings as the
|
|
74
|
+
* hooks. The service key isn't a property of it: it lives inside the `service` closure.
|
|
75
|
+
*/
|
|
76
|
+
export const withResolved = (custom, resolved) => ({
|
|
77
|
+
...custom,
|
|
78
|
+
[KEY]: resolved,
|
|
79
|
+
});
|
|
80
|
+
export const resolvedOf = (payload) => payload.config.custom?.[KEY];
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Config, Payload, PayloadRequest } from 'payload';
|
|
2
|
+
import { type Resolved } from './options.ts';
|
|
3
|
+
export type SyncResult = {
|
|
4
|
+
links: number;
|
|
5
|
+
synced: number;
|
|
6
|
+
moved: number;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Copies every link's totals from the service onto the link, 100 links a call, so admin lists can sort and filter by
|
|
10
|
+
* them. The service stays the source of truth; a link the service doesn't know keeps its last copy. Also moves any
|
|
11
|
+
* link whose stored destination no longer matches its document, such as after a rename whose move failed.
|
|
12
|
+
*/
|
|
13
|
+
export declare const syncLinkTotals: (payload: Payload, req?: PayloadRequest) => Promise<SyncResult>;
|
|
14
|
+
/**
|
|
15
|
+
* Adds the sync task, scheduled on its own queue, and an autoRun for that queue, keeping whatever jobs the host has.
|
|
16
|
+
* The task is there even when the plugin is turned off, so the jobs collection's schema doesn't change.
|
|
17
|
+
*/
|
|
18
|
+
export declare const withJobs: (jobs: Config['jobs'], resolved: Resolved) => Config['jobs'];
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { isKey } from '../client/key.js';
|
|
2
|
+
import { destinationOf, moveLinks } from './collections.js';
|
|
3
|
+
import { collectionOf, resolvedOf } from './options.js';
|
|
4
|
+
import { LINKS, SYNC_TASK } from './types.js';
|
|
5
|
+
/** The most keys `POST /v1/links/totals` takes at once. */
|
|
6
|
+
const BATCH = 100;
|
|
7
|
+
/**
|
|
8
|
+
* Copies every link's totals from the service onto the link, 100 links a call, so admin lists can sort and filter by
|
|
9
|
+
* them. The service stays the source of truth; a link the service doesn't know keeps its last copy. Also moves any
|
|
10
|
+
* link whose stored destination no longer matches its document, such as after a rename whose move failed.
|
|
11
|
+
*/
|
|
12
|
+
export const syncLinkTotals = async (payload, req) => {
|
|
13
|
+
const resolved = resolvedOf(payload);
|
|
14
|
+
if (!resolved)
|
|
15
|
+
throw new Error('cardware.link: the plugin is not installed on this Payload.');
|
|
16
|
+
let links = 0;
|
|
17
|
+
let synced = 0;
|
|
18
|
+
let moved = 0;
|
|
19
|
+
for (let page = 1;; page++) {
|
|
20
|
+
const found = await payload.find({
|
|
21
|
+
collection: LINKS,
|
|
22
|
+
depth: 0,
|
|
23
|
+
limit: BATCH,
|
|
24
|
+
page,
|
|
25
|
+
sort: 'createdAt',
|
|
26
|
+
select: { key: true, destination: true, target: true },
|
|
27
|
+
overrideAccess: true,
|
|
28
|
+
req,
|
|
29
|
+
});
|
|
30
|
+
const docs = found.docs;
|
|
31
|
+
links += docs.length;
|
|
32
|
+
const keys = docs.map(({ key }) => key).filter((key) => typeof key === 'string' && isKey(key));
|
|
33
|
+
if (keys.length > 0) {
|
|
34
|
+
const totals = await resolved.service('Totals were not synced', (client) => client.totals(keys));
|
|
35
|
+
const syncedAt = new Date().toISOString();
|
|
36
|
+
for (const doc of docs) {
|
|
37
|
+
const each = totals[doc.key];
|
|
38
|
+
if (!each)
|
|
39
|
+
continue;
|
|
40
|
+
await payload.db.updateOne({
|
|
41
|
+
collection: LINKS,
|
|
42
|
+
id: doc.id,
|
|
43
|
+
data: { scans: each.scans, uniqueScanners: each.uniqueScanners, saves: each.saves, syncedAt },
|
|
44
|
+
returning: false,
|
|
45
|
+
req,
|
|
46
|
+
});
|
|
47
|
+
synced++;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
moved += await realign(payload, resolved, docs, req);
|
|
51
|
+
if (!found.hasNextPage)
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
return { links, synced, moved };
|
|
55
|
+
};
|
|
56
|
+
/** Moves the links on one page whose stored destination differs from their document's. Answers how many moved. */
|
|
57
|
+
const realign = async (payload, resolved, links, req) => {
|
|
58
|
+
let moved = 0;
|
|
59
|
+
const bySlug = Map.groupBy(links, (link) => link.target?.relationTo);
|
|
60
|
+
for (const [slug, group] of bySlug) {
|
|
61
|
+
const collection = collectionOf(resolved, slug);
|
|
62
|
+
if (!collection)
|
|
63
|
+
continue;
|
|
64
|
+
const idOf = (link) => {
|
|
65
|
+
const value = link.target.value;
|
|
66
|
+
return typeof value === 'object' ? value.id : value;
|
|
67
|
+
};
|
|
68
|
+
const { docs } = await payload.find({
|
|
69
|
+
collection: collection.slug,
|
|
70
|
+
where: { id: { in: group.map(idOf) } },
|
|
71
|
+
depth: 0,
|
|
72
|
+
pagination: false,
|
|
73
|
+
overrideAccess: true,
|
|
74
|
+
showHiddenFields: true,
|
|
75
|
+
req,
|
|
76
|
+
});
|
|
77
|
+
const byId = new Map(docs.map((doc) => [String(doc.id), doc]));
|
|
78
|
+
for (const link of group) {
|
|
79
|
+
const doc = byId.get(String(idOf(link)));
|
|
80
|
+
if (!doc)
|
|
81
|
+
continue;
|
|
82
|
+
let next;
|
|
83
|
+
try {
|
|
84
|
+
next = destinationOf(collection, doc);
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
payload.logger.warn({ err: error, msg: `cardware.link: no destination for link ${link.key}` });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (link.destination === next)
|
|
91
|
+
continue;
|
|
92
|
+
const failed = await moveLinks({ payload, ...req }, resolved, next, [link]);
|
|
93
|
+
if (failed.length === 0)
|
|
94
|
+
moved++;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return moved;
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Adds the sync task, scheduled on its own queue, and an autoRun for that queue, keeping whatever jobs the host has.
|
|
101
|
+
* The task is there even when the plugin is turned off, so the jobs collection's schema doesn't change.
|
|
102
|
+
*/
|
|
103
|
+
export const withJobs = (jobs, resolved) => {
|
|
104
|
+
const sync = resolved.disabled ? undefined : resolved.sync;
|
|
105
|
+
const task = {
|
|
106
|
+
slug: SYNC_TASK,
|
|
107
|
+
label: 'Copy cardware.link totals',
|
|
108
|
+
retries: 0,
|
|
109
|
+
...(sync ? { schedule: [{ cron: sync.cron, queue: sync.queue }] } : {}),
|
|
110
|
+
handler: async ({ req }) => resolved.disabled
|
|
111
|
+
? { output: { links: 0, synced: 0, moved: 0 } }
|
|
112
|
+
: { output: await syncLinkTotals(req.payload, req) },
|
|
113
|
+
};
|
|
114
|
+
const tasks = [...(jobs?.tasks ?? []), task];
|
|
115
|
+
if (!sync?.autoRun)
|
|
116
|
+
return { ...jobs, tasks };
|
|
117
|
+
const ours = [{ cron: '* * * * *', queue: sync.queue }];
|
|
118
|
+
const autoRun = jobs?.autoRun;
|
|
119
|
+
return {
|
|
120
|
+
...jobs,
|
|
121
|
+
tasks,
|
|
122
|
+
autoRun: typeof autoRun === 'function'
|
|
123
|
+
? async (payload) => [...(await autoRun(payload)), ...ours]
|
|
124
|
+
: [...(autoRun ?? []), ...ours],
|
|
125
|
+
};
|
|
126
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { Access, CollectionSlug, DataFromCollectionSlug, PayloadRequest } from 'payload';
|
|
2
|
+
/** The links collection the plugin adds. */
|
|
3
|
+
export declare const LINKS = "tracked-links";
|
|
4
|
+
/** The join field the plugin adds to each target collection, listing the document's links. */
|
|
5
|
+
export declare const JOIN_FIELD = "trackedLinks";
|
|
6
|
+
/** The scheduled task that copies each link's totals from the service, and the queue it runs on. */
|
|
7
|
+
export declare const SYNC_TASK = "cardware-link-sync";
|
|
8
|
+
export declare const SYNC_QUEUE = "cardware-link";
|
|
9
|
+
/** Settings for one collection whose documents links open. */
|
|
10
|
+
export type TrackedCollection<S extends CollectionSlug = CollectionSlug> = {
|
|
11
|
+
access?: {
|
|
12
|
+
/**
|
|
13
|
+
* Which of this collection's documents a signed-in user may make links to and see the links of, written as
|
|
14
|
+
* Payload access: true for all, false for none, or a query. Managers always may. Default: managers only.
|
|
15
|
+
*/
|
|
16
|
+
links?: Access<DataFromCollectionSlug<S>>;
|
|
17
|
+
};
|
|
18
|
+
tracking: {
|
|
19
|
+
/**
|
|
20
|
+
* The URL a link to this document opens. Called when a link is made and whenever the document changes; when the
|
|
21
|
+
* answer changes, every link to the document is moved to it, so printed codes follow the document.
|
|
22
|
+
*/
|
|
23
|
+
destination: (doc: DataFromCollectionSlug<S>) => string;
|
|
24
|
+
code?: {
|
|
25
|
+
/** Draw the CardWare mark in the middle of the code. Default true. */
|
|
26
|
+
logo?: boolean;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
export type CardwareLinkOptions = {
|
|
31
|
+
/**
|
|
32
|
+
* Keeps the collection and fields, so the schema doesn't change, and stops talking to the service: no links are
|
|
33
|
+
* made or changed, nothing is synced and saves aren't reported. Links already printed keep working.
|
|
34
|
+
*/
|
|
35
|
+
disabled?: boolean;
|
|
36
|
+
access?: {
|
|
37
|
+
/**
|
|
38
|
+
* Users who see and manage every link, and the only ones who may delete one. In the admin's navigation only
|
|
39
|
+
* `req.user` is set. Default: any signed-in user, as Payload's own default.
|
|
40
|
+
*/
|
|
41
|
+
manage?: (args: {
|
|
42
|
+
req: PayloadRequest;
|
|
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>>;
|
|
49
|
+
};
|
|
50
|
+
admin?: {
|
|
51
|
+
/** Admin navigation group for the links collection. */
|
|
52
|
+
group?: string;
|
|
53
|
+
};
|
|
54
|
+
/** The collections links may open. */
|
|
55
|
+
collections: {
|
|
56
|
+
[S in CollectionSlug]?: TrackedCollection<S>;
|
|
57
|
+
};
|
|
58
|
+
tracking: {
|
|
59
|
+
/**
|
|
60
|
+
* The service and this app's key, such as `{ url: 'https://cardware.link', key: process.env.LINK_SERVICE_KEY }`.
|
|
61
|
+
* The key stays on the server. Without both, Payload still starts, and making a link fails with a clear message.
|
|
62
|
+
*/
|
|
63
|
+
service: {
|
|
64
|
+
url?: string;
|
|
65
|
+
key?: string;
|
|
66
|
+
};
|
|
67
|
+
/** The app's prefix on the service, the letter before the key in a link's URL. Default `c`. */
|
|
68
|
+
prefix?: string;
|
|
69
|
+
/**
|
|
70
|
+
* The scheduled copy of each link's totals, which admin lists sort and filter by. `false` turns the schedule off;
|
|
71
|
+
* `syncLinkTotals` still runs it on demand. Payload runs scheduled jobs only where crons are on
|
|
72
|
+
* (`getPayload({ config, cron: true })`).
|
|
73
|
+
*/
|
|
74
|
+
sync?: false | {
|
|
75
|
+
/** Default every 10 minutes: `*\/10 * * * *`. */
|
|
76
|
+
cron?: string;
|
|
77
|
+
/** Default `cardware-link`. */
|
|
78
|
+
queue?: string;
|
|
79
|
+
/** Add an autoRun for the queue, every minute. Default true. */
|
|
80
|
+
autoRun?: boolean;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* The address a phone's request came from, as the host's proxy reports it, forwarded with a save for the service's
|
|
84
|
+
* rate limit (it is never stored). Default: `X-Real-IP`, or `unknown`.
|
|
85
|
+
*/
|
|
86
|
+
callerAddress?: (headers: Headers) => string;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
/** A link as stored. `target` is polymorphic, so adding a collection changes no stored link. */
|
|
90
|
+
export type StoredLink = {
|
|
91
|
+
id: number | string;
|
|
92
|
+
label: string;
|
|
93
|
+
key: string;
|
|
94
|
+
url: string;
|
|
95
|
+
destination: string;
|
|
96
|
+
retired?: boolean | null;
|
|
97
|
+
target: {
|
|
98
|
+
relationTo: CollectionSlug;
|
|
99
|
+
value: number | string | {
|
|
100
|
+
id: number | string;
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
scans?: number | null;
|
|
104
|
+
uniqueScanners?: number | null;
|
|
105
|
+
saves?: number | null;
|
|
106
|
+
syncedAt?: string | null;
|
|
107
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** The links collection the plugin adds. */
|
|
2
|
+
export const LINKS = 'tracked-links';
|
|
3
|
+
/** The join field the plugin adds to each target collection, listing the document's links. */
|
|
4
|
+
export const JOIN_FIELD = 'trackedLinks';
|
|
5
|
+
/** The scheduled task that copies each link's totals from the service, and the queue it runs on. */
|
|
6
|
+
export const SYNC_TASK = 'cardware-link-sync';
|
|
7
|
+
export const SYNC_QUEUE = 'cardware-link';
|
package/package.json
CHANGED
|
@@ -1,6 +1,71 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@cardware/cardware-link",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "The client for cardware.link, CardWare's link-tracking service, and its Payload plugin.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cardware/cardware-link.git",
|
|
10
|
+
"directory": "packages/cardware-link"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cardware/cardware-link/tree/main/packages/cardware-link#readme",
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src/client",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"sideEffects": [
|
|
22
|
+
"*.css"
|
|
23
|
+
],
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"bun": "./src/client/index.ts",
|
|
27
|
+
"types": "./dist/client/index.d.ts",
|
|
28
|
+
"default": "./dist/client/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./payload": {
|
|
31
|
+
"types": "./dist/payload/index.d.ts",
|
|
32
|
+
"default": "./dist/payload/index.js"
|
|
33
|
+
},
|
|
34
|
+
"./payload/client": {
|
|
35
|
+
"types": "./dist/payload/client.d.ts",
|
|
36
|
+
"default": "./dist/payload/client.js"
|
|
37
|
+
},
|
|
38
|
+
"./payload/admin": {
|
|
39
|
+
"types": "./dist/payload/admin/index.d.ts",
|
|
40
|
+
"default": "./dist/payload/admin/index.js"
|
|
41
|
+
},
|
|
42
|
+
"./package.json": "./package.json"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && cp src/payload/admin/*.css dist/payload/admin/",
|
|
46
|
+
"prepublishOnly": "bun run build"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@payloadcms/ui": "^4.0.0-beta.9",
|
|
50
|
+
"payload": "^4.0.0-beta.9",
|
|
51
|
+
"react": "^19"
|
|
52
|
+
},
|
|
53
|
+
"peerDependenciesMeta": {
|
|
54
|
+
"@payloadcms/ui": {
|
|
55
|
+
"optional": true
|
|
56
|
+
},
|
|
57
|
+
"payload": {
|
|
58
|
+
"optional": true
|
|
59
|
+
},
|
|
60
|
+
"react": {
|
|
61
|
+
"optional": true
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"devDependencies": {
|
|
65
|
+
"@payloadcms/db-mongodb": "4.0.0-beta.9",
|
|
66
|
+
"@payloadcms/ui": "4.0.0-beta.9",
|
|
67
|
+
"@types/react": "19.2.14",
|
|
68
|
+
"payload": "4.0.0-beta.9",
|
|
69
|
+
"react": "19.2.4"
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
CodeOptions,
|
|
3
|
+
CreatedLink,
|
|
4
|
+
CreateLinkInput,
|
|
5
|
+
EventResult,
|
|
6
|
+
ForwardedRequest,
|
|
7
|
+
Link,
|
|
8
|
+
LinkDay,
|
|
9
|
+
LinkPage,
|
|
10
|
+
LinkPatch,
|
|
11
|
+
LinkTotals,
|
|
12
|
+
} from './types.ts'
|
|
13
|
+
|
|
14
|
+
export type LinkClientOptions = {
|
|
15
|
+
/** The service's origin, such as `https://cardware.link`. */
|
|
16
|
+
baseURL: string
|
|
17
|
+
/** The app's key, `cwl_live_…`. */
|
|
18
|
+
key: string
|
|
19
|
+
fetch?: typeof fetch
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A refusal from the service: its status and its `error` message. */
|
|
23
|
+
export class LinkServiceError extends Error {
|
|
24
|
+
constructor(
|
|
25
|
+
readonly status: number,
|
|
26
|
+
readonly body: unknown,
|
|
27
|
+
) {
|
|
28
|
+
const message =
|
|
29
|
+
body && typeof body === 'object' && 'error' in body ? String(body.error) : `status ${status}`
|
|
30
|
+
super(`cardware.link: ${message}`)
|
|
31
|
+
this.name = 'LinkServiceError'
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const query = (params: Record<string, string | number | boolean | undefined>) => {
|
|
36
|
+
const search = new URLSearchParams()
|
|
37
|
+
for (const [name, value] of Object.entries(params)) if (value !== undefined) search.set(name, String(value))
|
|
38
|
+
const text = search.toString()
|
|
39
|
+
return text ? `?${text}` : ''
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const createLinkClient = ({ baseURL, key, fetch: fetcher = fetch }: LinkClientOptions) => {
|
|
43
|
+
const origin = baseURL.replace(/\/+$/, '')
|
|
44
|
+
const call = async <T>(path: string, init: RequestInit = {}): Promise<T> => {
|
|
45
|
+
const response = await fetcher(`${origin}${path}`, {
|
|
46
|
+
...init,
|
|
47
|
+
headers: {
|
|
48
|
+
authorization: `Bearer ${key}`,
|
|
49
|
+
...(init.body ? { 'content-type': 'application/json' } : {}),
|
|
50
|
+
...init.headers,
|
|
51
|
+
},
|
|
52
|
+
})
|
|
53
|
+
const body = response.status === 204 ? undefined : await response.json().catch(() => undefined)
|
|
54
|
+
if (!response.ok) throw new LinkServiceError(response.status, body)
|
|
55
|
+
return body as T
|
|
56
|
+
}
|
|
57
|
+
const linkPath = (linkKey: string) => `/v1/links/${encodeURIComponent(linkKey)}`
|
|
58
|
+
|
|
59
|
+
/** The path of a link's code on the service, with its options. */
|
|
60
|
+
const codePath = (linkKey: string, options: CodeOptions = {}) => {
|
|
61
|
+
const { format = 'svg', ...rest } = options
|
|
62
|
+
return `${linkPath(linkKey)}/code.${format}${query({
|
|
63
|
+
...rest,
|
|
64
|
+
logo: rest.logo === false ? 0 : undefined,
|
|
65
|
+
})}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
/** Makes a link. With `idempotencyKey`, a retried create returns the first link instead of a second one. */
|
|
70
|
+
create: (input: CreateLinkInput, { idempotencyKey }: { idempotencyKey?: string } = {}) =>
|
|
71
|
+
call<CreatedLink>('/v1/links', {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
body: JSON.stringify(input),
|
|
74
|
+
headers: idempotencyKey ? { 'idempotency-key': idempotencyKey } : {},
|
|
75
|
+
}),
|
|
76
|
+
get: (linkKey: string) => call<Link>(linkPath(linkKey)),
|
|
77
|
+
list: (params: { externalRef?: string; prefix?: string; cursor?: string; limit?: number } = {}) =>
|
|
78
|
+
call<LinkPage>(`/v1/links${query(params)}`),
|
|
79
|
+
/** Totals for up to 100 links; links the app doesn't own are left out. */
|
|
80
|
+
totals: (keys: string[]) =>
|
|
81
|
+
call<{ totals: Record<string, LinkTotals> }>('/v1/links/totals', {
|
|
82
|
+
method: 'POST',
|
|
83
|
+
body: JSON.stringify({ keys }),
|
|
84
|
+
}).then(({ totals }) => totals),
|
|
85
|
+
days: (linkKey: string, range: { from?: string; to?: string } = {}) =>
|
|
86
|
+
call<{ days: LinkDay[] }>(`${linkPath(linkKey)}/days${query(range)}`).then(({ days }) => days),
|
|
87
|
+
/** Changes the label, the destination or whether the link is retired. The key and URL never change. */
|
|
88
|
+
update: (linkKey: string, patch: LinkPatch) =>
|
|
89
|
+
call<Link>(linkPath(linkKey), { method: 'PATCH', body: JSON.stringify(patch) }),
|
|
90
|
+
/** Reports a save, forwarding what the phone sent. */
|
|
91
|
+
reportSave: (linkKey: string, request: ForwardedRequest) =>
|
|
92
|
+
call<EventResult>(`${linkPath(linkKey)}/events`, {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
body: JSON.stringify({ kind: 'save', request }),
|
|
95
|
+
}),
|
|
96
|
+
/** The full URL of a link's code. Fetching it needs the app's key; `code` does that. */
|
|
97
|
+
codeURL: (linkKey: string, options?: CodeOptions) => `${origin}${codePath(linkKey, options)}`,
|
|
98
|
+
/** A link's code, as SVG text or PNG bytes, with its ETag. */
|
|
99
|
+
code: async (linkKey: string, options: CodeOptions = {}) => {
|
|
100
|
+
const response = await fetcher(`${origin}${codePath(linkKey, options)}`, {
|
|
101
|
+
headers: { authorization: `Bearer ${key}` },
|
|
102
|
+
})
|
|
103
|
+
if (!response.ok)
|
|
104
|
+
throw new LinkServiceError(response.status, await response.json().catch(() => undefined))
|
|
105
|
+
return {
|
|
106
|
+
body: new Uint8Array(await response.arrayBuffer()),
|
|
107
|
+
contentType: response.headers.get('content-type') ?? '',
|
|
108
|
+
etag: response.headers.get('etag'),
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export type LinkClient = ReturnType<typeof createLinkClient>
|
|
@@ -0,0 +1,21 @@
|
|
|
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
|
+
/**
|
|
5
|
+
* Ten characters, 50 bits: too many to guess, and short enough that `https://cardware.link/c/<key>` stays a version 4
|
|
6
|
+
* code at error correction H. Printed codes carry the key for good, so any key of an allowed length keeps opening.
|
|
7
|
+
*/
|
|
8
|
+
export const DEFAULT_KEY_LENGTH = 10
|
|
9
|
+
export const MIN_KEY_LENGTH = 8
|
|
10
|
+
export const MAX_KEY_LENGTH = 32
|
|
11
|
+
|
|
12
|
+
/** A prefix is one lower-case letter: `c` for cards, and one each for other apps. */
|
|
13
|
+
export const isPrefix = (value: string) => /^[a-z]$/.test(value)
|
|
14
|
+
|
|
15
|
+
export const newKey = (length = DEFAULT_KEY_LENGTH) =>
|
|
16
|
+
Array.from(crypto.getRandomValues(new Uint8Array(length)), (byte) => KEY_ALPHABET[byte & 31]).join('')
|
|
17
|
+
|
|
18
|
+
export const isKey = (value: string) =>
|
|
19
|
+
value.length >= MIN_KEY_LENGTH &&
|
|
20
|
+
value.length <= MAX_KEY_LENGTH &&
|
|
21
|
+
[...value].every((char) => KEY_ALPHABET.includes(char))
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export type Device = 'ios' | 'android' | 'other'
|
|
2
|
+
|
|
3
|
+
export type EventKind = 'scan' | 'save'
|
|
4
|
+
|
|
5
|
+
/** A link's three counts. Unique scanners are scans from a browser that had not opened the link before. */
|
|
6
|
+
export type LinkTotals = { scans: number; uniqueScanners: number; saves: number }
|
|
7
|
+
|
|
8
|
+
export type Link = {
|
|
9
|
+
key: string
|
|
10
|
+
prefix: string
|
|
11
|
+
url: string
|
|
12
|
+
destination: string
|
|
13
|
+
label: string | null
|
|
14
|
+
externalRef: string | null
|
|
15
|
+
metadata: Record<string, unknown>
|
|
16
|
+
retired: boolean
|
|
17
|
+
createdAt: string
|
|
18
|
+
totals: LinkTotals
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type CreatedLink = Pick<Link, 'key' | 'url' | 'destination' | 'createdAt'>
|
|
22
|
+
|
|
23
|
+
export type CreateLinkInput = {
|
|
24
|
+
prefix: string
|
|
25
|
+
destination: string
|
|
26
|
+
label?: string
|
|
27
|
+
externalRef?: string
|
|
28
|
+
metadata?: Record<string, unknown>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export type LinkPatch = { label?: string | null; retired?: boolean; destination?: string }
|
|
32
|
+
|
|
33
|
+
export type LinkPage = { links: Link[]; nextCursor: string | null }
|
|
34
|
+
|
|
35
|
+
export type LinkDay = { day: string } & LinkTotals
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What the phone sent with a request, forwarded by the app so the service judges a save as it judges a scan. The
|
|
39
|
+
* address is used for the rate limit and never stored.
|
|
40
|
+
*/
|
|
41
|
+
export type ForwardedRequest = {
|
|
42
|
+
userAgent: string
|
|
43
|
+
secPurpose?: string
|
|
44
|
+
purpose?: string
|
|
45
|
+
address: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type NotCounted = 'retired' | 'program' | 'over-limit'
|
|
49
|
+
|
|
50
|
+
export type EventResult = { counted: true } | { counted: false; reason: NotCounted }
|
|
51
|
+
|
|
52
|
+
export type CodeOptions =
|
|
53
|
+
| { format?: 'svg'; size?: number; mm?: number; logo?: boolean }
|
|
54
|
+
| { format: 'png'; size?: number; mm?: number; dpi?: number; logo?: boolean }
|