@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.
@@ -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;
@@ -0,0 +1,325 @@
1
+ import { APIError, } from 'payload';
2
+ import { LinkServiceError } from '../client/client.js';
3
+ import { linksWhere, mayLinkTo } from './access.js';
4
+ import { endpoints } from './endpoints.js';
5
+ import { collectionOf } from './options.js';
6
+ import { JOIN_FIELD, LINKS } from './types.js';
7
+ const nobody = () => false;
8
+ /** Where the admin finds the link's panel: the package's own admin entry, which the host's import map loads. */
9
+ export const LINK_PANEL = '@cardware/cardware-link/payload/admin#LinkPanel';
10
+ /** Set on a request while a link it made on the service hasn't been stored yet, so a failed store can retire it. */
11
+ const UNSTORED = 'cardwareLinkUnstored';
12
+ /**
13
+ * A count, copied from the service by the sync job and never written through the API. Shown as a list column, so
14
+ * lists sort and filter by it; the link's own screen reads the live totals instead, so not again as a field.
15
+ */
16
+ const total = (name, label) => ({
17
+ name,
18
+ label,
19
+ type: 'number',
20
+ defaultValue: 0,
21
+ access: { create: nobody, update: nobody },
22
+ admin: { readOnly: true, condition: () => false },
23
+ });
24
+ const idOf = (value) => value && typeof value === 'object' ? value.id : value;
25
+ const targetWhere = (relationTo, id) => ({
26
+ and: [{ 'target.relationTo': { equals: relationTo } }, { 'target.value': { equals: id } }],
27
+ });
28
+ /** The service keeps a label of at most 200 characters, and Payload requires one. */
29
+ const checkedLabel = (value) => {
30
+ const label = typeof value === 'string' ? value.trim() : '';
31
+ if (!label)
32
+ throw new APIError('A link needs a label.', 400);
33
+ if (label.length > 200)
34
+ throw new APIError('A link’s label is at most 200 characters.', 400);
35
+ return label;
36
+ };
37
+ /**
38
+ * The whole target document, as stored: re-read with access overridden, hidden fields shown and no `select`, so the
39
+ * destination never comes from a trimmed copy such as the one a hook receives.
40
+ */
41
+ export const targetDoc = (req, slug, id) => req.payload.findByID({
42
+ collection: slug,
43
+ id,
44
+ depth: 0,
45
+ disableErrors: true,
46
+ overrideAccess: true,
47
+ showHiddenFields: true,
48
+ req,
49
+ });
50
+ /** Makes the link on the service, from the target document's destination. */
51
+ const create = async (req, resolved, data) => {
52
+ const id = idOf(data.target?.value);
53
+ const collection = collectionOf(resolved, data.target?.relationTo);
54
+ if (!data.target || id === undefined || id === '' || !collection)
55
+ throw new APIError('A link needs a target.', 400);
56
+ const label = checkedLabel(data.label);
57
+ // No user: trusted server code, which access already let through.
58
+ if (req.user && !(await mayLinkTo(req, resolved, collection.slug, id)))
59
+ throw new APIError('You may not make links to this.', 403);
60
+ const doc = await targetDoc(req, collection.slug, id);
61
+ if (!doc)
62
+ throw new APIError('The link’s target does not exist.', 400);
63
+ const destination = destinationOf(collection, doc);
64
+ const input = { prefix: resolved.prefix, destination, label, externalRef: `${collection.slug}:${id}` };
65
+ // One idempotency key per create: when the answer is lost on the way back, the retry gets the same link back
66
+ // instead of making a second one.
67
+ const idempotencyKey = `${collection.slug}:${id}:${crypto.randomUUID()}`;
68
+ const created = await resolved.service('The link was not made', async (client) => {
69
+ let made;
70
+ try {
71
+ made = await client.create(input, { idempotencyKey });
72
+ }
73
+ catch (error) {
74
+ if (error instanceof LinkServiceError)
75
+ throw error;
76
+ made = await client.create(input, { idempotencyKey });
77
+ }
78
+ req.context[UNSTORED] = made.key;
79
+ // The service makes every link active: one made retired is retired straight away.
80
+ if (data.retired === true)
81
+ await client.update(made.key, { retired: true });
82
+ return made;
83
+ });
84
+ return { label, key: created.key, url: created.url, destination: created.destination };
85
+ };
86
+ export const destinationOf = (collection, doc) => {
87
+ try {
88
+ return collection.destination(doc);
89
+ }
90
+ catch (error) {
91
+ throw new APIError(`The link’s destination could not be worked out: ${error instanceof Error ? error.message : String(error)}`, 400);
92
+ }
93
+ };
94
+ export const linksCollection = (resolved) => ({
95
+ slug: LINKS,
96
+ labels: { singular: 'Tracked link', plural: 'Tracked links' },
97
+ admin: {
98
+ useAsTitle: 'label',
99
+ defaultColumns: ['label', 'target', 'scans', 'uniqueScanners', 'saves', 'retired', 'syncedAt'],
100
+ group: resolved.group,
101
+ description: 'A link and code made by cardware.link, counted there. Printed codes keep working for good: retire a link rather than delete it. Counts in this list are copied every 10 minutes.',
102
+ },
103
+ access: {
104
+ read: ({ req }) => linksWhere(req, resolved),
105
+ create: ({ req }) => Boolean(req.user),
106
+ update: ({ req }) => linksWhere(req, resolved),
107
+ delete: ({ req }) => resolved.manages(req),
108
+ ...resolved.access,
109
+ },
110
+ versions: false,
111
+ endpoints: endpoints(resolved),
112
+ hooks: {
113
+ beforeChange: [
114
+ async ({ data, operation, originalDoc, req }) => {
115
+ if (operation === 'create')
116
+ return { ...data, ...(await create(req, resolved, data)) };
117
+ const original = originalDoc;
118
+ // What a printed code opens, and the link it carries, are fixed when the link is made.
119
+ const fixed = {
120
+ key: original.key,
121
+ url: original.url,
122
+ target: original.target,
123
+ destination: original.destination,
124
+ };
125
+ const patch = {};
126
+ // Checked here, because Payload validates fields only after this hook, once the service has the change.
127
+ if (data.label !== undefined && data.label !== original.label)
128
+ patch.label = checkedLabel(data.label);
129
+ if (typeof data.retired === 'boolean' && data.retired !== Boolean(original.retired))
130
+ patch.retired = data.retired;
131
+ if (original.key && Object.keys(patch).length > 0)
132
+ await resolved.service('The change was not saved', (client) => client.update(original.key, patch));
133
+ return { ...data, ...(patch.label ? { label: patch.label } : {}), ...fixed };
134
+ },
135
+ ],
136
+ afterChange: [
137
+ ({ doc, operation, req }) => {
138
+ if (operation === 'create')
139
+ delete req.context[UNSTORED];
140
+ return doc;
141
+ },
142
+ ],
143
+ afterError: [
144
+ async ({ req }) => {
145
+ // The service made a link that was never stored here: retire it, so nothing counts against a link nobody has.
146
+ const key = req.context?.[UNSTORED];
147
+ if (typeof key !== 'string')
148
+ return;
149
+ delete req.context[UNSTORED];
150
+ await resolved
151
+ .service('An unstored link was not retired', (client) => client.update(key, { retired: true }))
152
+ .catch((error) => req.payload.logger.error({ err: error, msg: `cardware.link: link ${key} made but not stored` }));
153
+ },
154
+ ],
155
+ beforeDelete: [
156
+ async ({ id, req }) => {
157
+ const link = (await req.payload.findByID({
158
+ collection: LINKS,
159
+ id,
160
+ depth: 0,
161
+ disableErrors: true,
162
+ overrideAccess: true,
163
+ req,
164
+ }));
165
+ if (!link?.key)
166
+ return;
167
+ try {
168
+ await resolved.service('The link was not deleted', (client) => client.update(link.key, { retired: true }));
169
+ }
170
+ catch (error) {
171
+ // Gone from the service already: nothing left to retire.
172
+ if (error instanceof APIError && error.status === 404)
173
+ return;
174
+ throw error;
175
+ }
176
+ },
177
+ ],
178
+ },
179
+ fields: [
180
+ {
181
+ name: 'panel',
182
+ type: 'ui',
183
+ admin: { components: { Field: LINK_PANEL } },
184
+ },
185
+ {
186
+ name: 'label',
187
+ type: 'text',
188
+ required: true,
189
+ admin: { description: 'Where this link goes, such as “Money20/20 Las Vegas”. Only shown here.' },
190
+ },
191
+ {
192
+ name: 'target',
193
+ type: 'relationship',
194
+ relationTo: resolved.collections.map(({ slug }) => slug),
195
+ required: true,
196
+ access: { update: nobody },
197
+ admin: { description: 'What the link opens. Fixed once the link is made.' },
198
+ filterOptions: async ({ relationTo, req }) => resolved.manages(req) || ((await collectionOf(resolved, relationTo)?.linkable(req)) ?? false),
199
+ },
200
+ {
201
+ name: 'retired',
202
+ type: 'checkbox',
203
+ defaultValue: false,
204
+ admin: {
205
+ position: 'sidebar',
206
+ description: 'A retired link still opens its destination, so printed copies keep working, and counts nothing.',
207
+ },
208
+ },
209
+ { name: 'key', type: 'text', unique: true, index: true, admin: { readOnly: true, position: 'sidebar' } },
210
+ { name: 'url', label: 'URL', type: 'text', admin: { readOnly: true, position: 'sidebar' } },
211
+ {
212
+ name: 'destination',
213
+ type: 'text',
214
+ admin: {
215
+ readOnly: true,
216
+ position: 'sidebar',
217
+ description: 'Where the link opens. Follows the target when it changes.',
218
+ },
219
+ },
220
+ total('scans', 'Scans'),
221
+ total('uniqueScanners', 'Unique scanners'),
222
+ total('saves', 'Saves'),
223
+ {
224
+ name: 'syncedAt',
225
+ label: 'Counts copied',
226
+ type: 'date',
227
+ access: { create: nobody, update: nobody },
228
+ admin: {
229
+ readOnly: true,
230
+ position: 'sidebar',
231
+ date: { pickerAppearance: 'dayAndTime' },
232
+ description: 'When the counts in lists were last copied from cardware.link.',
233
+ },
234
+ },
235
+ ],
236
+ });
237
+ /** A target with links can't be deleted: printed codes would lose what they open. A manager deletes the links first. */
238
+ export const refuseDeleteWhileLinked = (relationTo) => async ({ id, req }) => {
239
+ const { totalDocs } = await req.payload.count({
240
+ collection: LINKS,
241
+ where: targetWhere(relationTo, id),
242
+ overrideAccess: true,
243
+ req,
244
+ });
245
+ if (totalDocs > 0)
246
+ throw new APIError(`This has ${totalDocs} tracked link${totalDocs === 1 ? '' : 's'}. Printed codes open it, so a manager must delete ${totalDocs === 1 ? 'that link' : 'those links'} first.`, 400);
247
+ };
248
+ /**
249
+ * Moves each link whose stored destination no longer matches its document's to the document's current one, on the
250
+ * service and then in the stored copy. Answers the failures; a later attempt starts again from the stored copies.
251
+ */
252
+ export const moveLinks = async (req, resolved, next, links) => {
253
+ const failed = [];
254
+ for (const link of links.filter((each) => each.key && each.destination !== next)) {
255
+ try {
256
+ await resolved.service('Not moved', (client) => client.update(link.key, { destination: next }));
257
+ await req.payload.db.updateOne({
258
+ collection: LINKS,
259
+ id: link.id,
260
+ data: { destination: next },
261
+ returning: false,
262
+ req,
263
+ });
264
+ }
265
+ catch (error) {
266
+ failed.push(error instanceof Error ? error.message : String(error));
267
+ req.payload.logger.error({ err: error, msg: `cardware.link: link ${link.key} not moved to ${next}` });
268
+ }
269
+ }
270
+ return failed;
271
+ };
272
+ /**
273
+ * Moves every link to a document whose destination no longer matches the document. Compares with each link's own
274
+ * copy of its destination, not the previous document, so a save after a failed move tries again (and so does the
275
+ * sync job). Reads the document again in full: the one a hook receives may be trimmed by the caller's `select`.
276
+ */
277
+ export const followDestination = (resolved, collection) => async ({ doc, operation, req }) => {
278
+ if (operation !== 'update' || resolved.disabled)
279
+ return doc;
280
+ const { docs } = await req.payload.find({
281
+ collection: LINKS,
282
+ where: targetWhere(collection.slug, doc.id),
283
+ depth: 0,
284
+ pagination: false,
285
+ overrideAccess: true,
286
+ req,
287
+ });
288
+ const links = docs;
289
+ if (links.length === 0)
290
+ return doc;
291
+ const stored = await targetDoc(req, collection.slug, doc.id);
292
+ if (!stored)
293
+ return doc;
294
+ const next = destinationOf(collection, stored);
295
+ const moving = links.filter((link) => link.key && link.destination !== next);
296
+ const failed = await moveLinks(req, resolved, next, moving);
297
+ if (failed.length > 0)
298
+ 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);
299
+ return doc;
300
+ };
301
+ /**
302
+ * The links to a document, on the document's own screen, where a new one can be made with the target filled in.
303
+ * Only a signed-in reader gets them: see `withoutLinksForThePublic`.
304
+ */
305
+ export const linksJoinField = () => ({
306
+ name: JOIN_FIELD,
307
+ label: 'Tracked links',
308
+ type: 'join',
309
+ collection: LINKS,
310
+ on: 'target',
311
+ admin: {
312
+ allowCreate: true,
313
+ defaultColumns: ['label', 'scans', 'uniqueScanners', 'saves', 'retired'],
314
+ },
315
+ });
316
+ /**
317
+ * Pages that render a document for the public read it on the server with no user, often with access overridden,
318
+ * and may hand the whole record to the browser. Without a user, a document comes back without its links.
319
+ */
320
+ export const withoutLinksForThePublic = ({ doc, req }) => {
321
+ if (req.user || !(JOIN_FIELD in doc))
322
+ return doc;
323
+ const { [JOIN_FIELD]: _links, ...rest } = doc;
324
+ return rest;
325
+ };
@@ -0,0 +1,3 @@
1
+ import { type Endpoint } from 'payload';
2
+ import { type Resolved } from './options.ts';
3
+ export declare const endpoints: (resolved: Resolved) => Endpoint[];
@@ -0,0 +1,113 @@
1
+ import { APIError } from 'payload';
2
+ import { isKey } from '../client/key.js';
3
+ import { collectionOf } from './options.js';
4
+ import { LINKS } from './types.js';
5
+ const NO_STORE = { 'cache-control': 'no-store' };
6
+ const failure = (error, headers = {}) => {
7
+ const status = error instanceof APIError ? error.status : 500;
8
+ const message = error instanceof APIError ? error.message : 'Something went wrong.';
9
+ return Response.json({ error: message }, { status, headers });
10
+ };
11
+ const numberOf = (params, name) => {
12
+ const raw = params.get(name);
13
+ if (raw === null)
14
+ return undefined;
15
+ const value = Number(raw);
16
+ if (raw === '' || !Number.isFinite(value))
17
+ throw new APIError(`${name} must be a number.`, 400);
18
+ return value;
19
+ };
20
+ /** What a request for a code asks for, read from its query string. The service checks the numbers. */
21
+ const codeAsk = (params) => {
22
+ const format = params.get('format') ?? 'svg';
23
+ if (format !== 'svg' && format !== 'png')
24
+ throw new APIError('format must be svg or png.', 400);
25
+ const download = params.get('download') ?? '0';
26
+ if (download !== '0' && download !== '1')
27
+ throw new APIError('download must be 0 or 1.', 400);
28
+ const size = numberOf(params, 'size');
29
+ const mm = numberOf(params, 'mm');
30
+ const options = format === 'png' ? { format, size, mm, dpi: numberOf(params, 'dpi') } : { format, size, mm };
31
+ return { options, download: download === '1' };
32
+ };
33
+ /** A file name from the link's label: ASCII letters, digits and dashes. */
34
+ const fileNameOf = (link, format) => {
35
+ const label = link.label
36
+ .normalize('NFKD')
37
+ .replaceAll(/[^\w\s-]/g, '')
38
+ .trim()
39
+ .replaceAll(/[\s_]+/g, '-')
40
+ .toLowerCase();
41
+ return `${label ? `${label}-` : ''}${link.key}.${format}`;
42
+ };
43
+ export const endpoints = (resolved) => [
44
+ {
45
+ /**
46
+ * `GET /api/tracked-links/:id/code?format=svg|png&size=&mm=&dpi=&download=1`: the link's code, drawn by the service
47
+ * and fetched here with the app's key, so the key never reaches the browser. Only for users who may read the link.
48
+ */
49
+ path: '/:id/code',
50
+ method: 'get',
51
+ handler: async (req) => {
52
+ try {
53
+ if (!req.user)
54
+ throw new APIError('Sign in to see this code.', 401);
55
+ const link = (await req.payload.findByID({
56
+ collection: LINKS,
57
+ id: String(req.routeParams?.id ?? ''),
58
+ depth: 0,
59
+ disableErrors: true,
60
+ overrideAccess: false,
61
+ req,
62
+ }));
63
+ if (!link?.key)
64
+ throw new APIError('No such link.', 404);
65
+ const { options, download } = codeAsk(new URL(req.url ?? '', 'http://local').searchParams);
66
+ options.logo = collectionOf(resolved, link.target?.relationTo)?.logo ?? true;
67
+ const code = await resolved.service('The code could not be drawn', (client) => client.code(link.key, options));
68
+ const format = options.format ?? 'svg';
69
+ return new Response(code.body, {
70
+ headers: {
71
+ 'content-type': code.contentType,
72
+ 'cache-control': 'private, no-cache',
73
+ ...(code.etag ? { etag: code.etag } : {}),
74
+ 'content-disposition': `${download ? 'attachment' : 'inline'}; filename="${fileNameOf(link, format)}"`,
75
+ },
76
+ });
77
+ }
78
+ catch (error) {
79
+ return failure(error);
80
+ }
81
+ },
82
+ },
83
+ {
84
+ /**
85
+ * `POST /api/tracked-links/save` with `{ key }`: a phone's browser reporting that it saved what a link opened.
86
+ * Forwarded to the service with what the phone sent, so the service judges it as it judges a scan, and answered
87
+ * with the service's status: 201 counted, 202 not counted, 400 or 404 refused. Public: the key is all it takes.
88
+ */
89
+ path: '/save',
90
+ method: 'post',
91
+ handler: async (req) => {
92
+ try {
93
+ const body = await req.json?.().catch(() => undefined);
94
+ const key = body && typeof body === 'object' && 'key' in body ? body.key : undefined;
95
+ if (typeof key !== 'string' || !isKey(key))
96
+ throw new APIError('The body must be { key } with a link’s key.', 400);
97
+ const headers = req.headers;
98
+ const result = await resolved.service('The save was not reported', (client) => client.reportSave(key, {
99
+ userAgent: headers.get('user-agent') ?? '',
100
+ secPurpose: headers.get('sec-purpose') ?? undefined,
101
+ purpose: headers.get('purpose') ?? undefined,
102
+ address: resolved.callerAddress(headers),
103
+ }));
104
+ return Response.json(result, { status: result.counted ? 201 : 202, headers: NO_STORE });
105
+ }
106
+ catch (error) {
107
+ if (!(error instanceof APIError) || error.status >= 500)
108
+ req.payload.logger.warn({ err: error, msg: 'cardware.link: a save was not reported' });
109
+ return failure(error, NO_STORE);
110
+ }
111
+ },
112
+ },
113
+ ];
@@ -0,0 +1,11 @@
1
+ import type { Plugin } from 'payload';
2
+ import type { CardwareLinkOptions } from './types.ts';
3
+ export { LINK_PANEL } from './collections.ts';
4
+ export { type SyncResult, syncLinkTotals } from './sync.ts';
5
+ export * from './types.ts';
6
+ /**
7
+ * cardware.link for Payload: a `tracked-links` collection whose links are made, moved, retired and counted by the
8
+ * service, a list of links on each tracked document, a scheduled copy of the counts for admin lists, and the
9
+ * endpoints the admin's code and a phone's saves go through. See the package's README.
10
+ */
11
+ export declare const cardwareLinkPlugin: (options: CardwareLinkOptions) => Plugin;
@@ -0,0 +1,49 @@
1
+ import { followDestination, linksCollection, linksJoinField, refuseDeleteWhileLinked, withoutLinksForThePublic, } from './collections.js';
2
+ import { collectionOf, resolve, withResolved } from './options.js';
3
+ import { withJobs } from './sync.js';
4
+ export { LINK_PANEL } from './collections.js';
5
+ export { syncLinkTotals } from './sync.js';
6
+ export * from './types.js';
7
+ /**
8
+ * cardware.link for Payload: a `tracked-links` collection whose links are made, moved, retired and counted by the
9
+ * service, a list of links on each tracked document, a scheduled copy of the counts for admin lists, and the
10
+ * endpoints the admin's code and a phone's saves go through. See the package's README.
11
+ */
12
+ export const cardwareLinkPlugin = (options) => (config) => {
13
+ const resolved = resolve(options);
14
+ const known = new Set((config.collections ?? []).map(({ slug }) => slug));
15
+ for (const { slug } of resolved.collections)
16
+ if (!known.has(slug))
17
+ throw new Error(`cardware.link: there is no collection "${slug}".`);
18
+ return {
19
+ ...config,
20
+ custom: withResolved(config.custom, resolved),
21
+ collections: [
22
+ ...(config.collections ?? []).map((collection) => {
23
+ const tracked = collectionOf(resolved, collection.slug);
24
+ if (!tracked)
25
+ return collection;
26
+ return {
27
+ ...collection,
28
+ fields: [...collection.fields, linksJoinField()],
29
+ hooks: {
30
+ ...collection.hooks,
31
+ afterRead: [...(collection.hooks?.afterRead ?? []), withoutLinksForThePublic],
32
+ afterChange: [...(collection.hooks?.afterChange ?? []), followDestination(resolved, tracked)],
33
+ beforeDelete: [
34
+ ...(collection.hooks?.beforeDelete ?? []),
35
+ refuseDeleteWhileLinked(tracked.slug),
36
+ ],
37
+ },
38
+ };
39
+ }),
40
+ linksCollection(resolved),
41
+ ],
42
+ jobs: withJobs(config.jobs, resolved),
43
+ onInit: async (payload) => {
44
+ await config.onInit?.(payload);
45
+ if (!resolved.disabled && !resolved.configured)
46
+ payload.logger.warn('cardware.link: tracking.service has no URL or key, so making and changing links will fail until both are set.');
47
+ },
48
+ };
49
+ };
@@ -0,0 +1,46 @@
1
+ import { APIError, type CollectionSlug, type Payload, type PayloadRequest, type Where } from 'payload';
2
+ import { type LinkClient } from '../client/client.ts';
3
+ import { type CardwareLinkOptions } from './types.ts';
4
+ export type ResolvedCollection = {
5
+ slug: CollectionSlug;
6
+ /** Which documents the signed-in user may link to, from the collection's `access.links`. */
7
+ linkable: (req: PayloadRequest) => Promise<boolean | Where>;
8
+ destination: (doc: Record<string, unknown>) => string;
9
+ logo: boolean;
10
+ };
11
+ /** The options with every default filled in, checked once when Payload starts. */
12
+ export type Resolved = {
13
+ disabled: boolean;
14
+ /** Whether the request's user manages every link. Takes a real request, or `{ user }` where only that is known. */
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'];
18
+ group?: string;
19
+ prefix: string;
20
+ collections: ResolvedCollection[];
21
+ /** Whether a service URL and key were given. */
22
+ configured: boolean;
23
+ /**
24
+ * Runs `call` with the service's client, turning a failure into an `APIError` that says what didn't happen. The
25
+ * client, and the key inside it, never leave this closure.
26
+ */
27
+ service: <T>(what: string, call: (client: LinkClient) => Promise<T>) => Promise<T>;
28
+ callerAddress: (headers: Headers) => string;
29
+ sync?: {
30
+ cron: string;
31
+ queue: string;
32
+ autoRun: boolean;
33
+ };
34
+ };
35
+ /** Why a call to the service failed, in words for the person who asked for it. */
36
+ export declare const serviceFailure: (what: string, error: unknown) => APIError<any>;
37
+ export declare const resolve: (options: CardwareLinkOptions) => Resolved;
38
+ export declare const collectionOf: (resolved: Resolved, slug: string | undefined) => ResolvedCollection | undefined;
39
+ /**
40
+ * The resolved options, kept on the server-only `config.custom` so the admin panel reads the same settings as the
41
+ * hooks. The service key isn't a property of it: it lives inside the `service` closure.
42
+ */
43
+ export declare const withResolved: (custom: Record<string, unknown> | undefined, resolved: Resolved) => {
44
+ cardwareLink: Resolved;
45
+ };
46
+ export declare const resolvedOf: (payload: Payload) => Resolved | undefined;