@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 +21 -0
- package/README.md +114 -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.d.ts +7 -0
- package/dist/payload/admin/link-panel.js +40 -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 +324 -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 +44 -0
- package/dist/payload/options.js +79 -0
- package/dist/payload/sync.d.ts +18 -0
- package/dist/payload/sync.js +126 -0
- package/dist/payload/types.d.ts +102 -0
- package/dist/payload/types.js +7 -0
- package/package.json +64 -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,324 @@
|
|
|
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
|
+
},
|
|
109
|
+
versions: false,
|
|
110
|
+
endpoints: endpoints(resolved),
|
|
111
|
+
hooks: {
|
|
112
|
+
beforeChange: [
|
|
113
|
+
async ({ data, operation, originalDoc, req }) => {
|
|
114
|
+
if (operation === 'create')
|
|
115
|
+
return { ...data, ...(await create(req, resolved, data)) };
|
|
116
|
+
const original = originalDoc;
|
|
117
|
+
// What a printed code opens, and the link it carries, are fixed when the link is made.
|
|
118
|
+
const fixed = {
|
|
119
|
+
key: original.key,
|
|
120
|
+
url: original.url,
|
|
121
|
+
target: original.target,
|
|
122
|
+
destination: original.destination,
|
|
123
|
+
};
|
|
124
|
+
const patch = {};
|
|
125
|
+
// Checked here, because Payload validates fields only after this hook, once the service has the change.
|
|
126
|
+
if (data.label !== undefined && data.label !== original.label)
|
|
127
|
+
patch.label = checkedLabel(data.label);
|
|
128
|
+
if (typeof data.retired === 'boolean' && data.retired !== Boolean(original.retired))
|
|
129
|
+
patch.retired = data.retired;
|
|
130
|
+
if (original.key && Object.keys(patch).length > 0)
|
|
131
|
+
await resolved.service('The change was not saved', (client) => client.update(original.key, patch));
|
|
132
|
+
return { ...data, ...(patch.label ? { label: patch.label } : {}), ...fixed };
|
|
133
|
+
},
|
|
134
|
+
],
|
|
135
|
+
afterChange: [
|
|
136
|
+
({ doc, operation, req }) => {
|
|
137
|
+
if (operation === 'create')
|
|
138
|
+
delete req.context[UNSTORED];
|
|
139
|
+
return doc;
|
|
140
|
+
},
|
|
141
|
+
],
|
|
142
|
+
afterError: [
|
|
143
|
+
async ({ req }) => {
|
|
144
|
+
// The service made a link that was never stored here: retire it, so nothing counts against a link nobody has.
|
|
145
|
+
const key = req.context?.[UNSTORED];
|
|
146
|
+
if (typeof key !== 'string')
|
|
147
|
+
return;
|
|
148
|
+
delete req.context[UNSTORED];
|
|
149
|
+
await resolved
|
|
150
|
+
.service('An unstored link was not retired', (client) => client.update(key, { retired: true }))
|
|
151
|
+
.catch((error) => req.payload.logger.error({ err: error, msg: `cardware.link: link ${key} made but not stored` }));
|
|
152
|
+
},
|
|
153
|
+
],
|
|
154
|
+
beforeDelete: [
|
|
155
|
+
async ({ id, req }) => {
|
|
156
|
+
const link = (await req.payload.findByID({
|
|
157
|
+
collection: LINKS,
|
|
158
|
+
id,
|
|
159
|
+
depth: 0,
|
|
160
|
+
disableErrors: true,
|
|
161
|
+
overrideAccess: true,
|
|
162
|
+
req,
|
|
163
|
+
}));
|
|
164
|
+
if (!link?.key)
|
|
165
|
+
return;
|
|
166
|
+
try {
|
|
167
|
+
await resolved.service('The link was not deleted', (client) => client.update(link.key, { retired: true }));
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
// Gone from the service already: nothing left to retire.
|
|
171
|
+
if (error instanceof APIError && error.status === 404)
|
|
172
|
+
return;
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
],
|
|
177
|
+
},
|
|
178
|
+
fields: [
|
|
179
|
+
{
|
|
180
|
+
name: 'panel',
|
|
181
|
+
type: 'ui',
|
|
182
|
+
admin: { components: { Field: LINK_PANEL } },
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
name: 'label',
|
|
186
|
+
type: 'text',
|
|
187
|
+
required: true,
|
|
188
|
+
admin: { description: 'Where this link goes, such as “Money20/20 Las Vegas”. Only shown here.' },
|
|
189
|
+
},
|
|
190
|
+
{
|
|
191
|
+
name: 'target',
|
|
192
|
+
type: 'relationship',
|
|
193
|
+
relationTo: resolved.collections.map(({ slug }) => slug),
|
|
194
|
+
required: true,
|
|
195
|
+
access: { update: nobody },
|
|
196
|
+
admin: { description: 'What the link opens. Fixed once the link is made.' },
|
|
197
|
+
filterOptions: async ({ relationTo, req }) => resolved.manages(req) || ((await collectionOf(resolved, relationTo)?.linkable(req)) ?? false),
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
name: 'retired',
|
|
201
|
+
type: 'checkbox',
|
|
202
|
+
defaultValue: false,
|
|
203
|
+
admin: {
|
|
204
|
+
position: 'sidebar',
|
|
205
|
+
description: 'A retired link still opens its destination, so printed copies keep working, and counts nothing.',
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
{ name: 'key', type: 'text', unique: true, index: true, admin: { readOnly: true, position: 'sidebar' } },
|
|
209
|
+
{ name: 'url', label: 'URL', type: 'text', admin: { readOnly: true, position: 'sidebar' } },
|
|
210
|
+
{
|
|
211
|
+
name: 'destination',
|
|
212
|
+
type: 'text',
|
|
213
|
+
admin: {
|
|
214
|
+
readOnly: true,
|
|
215
|
+
position: 'sidebar',
|
|
216
|
+
description: 'Where the link opens. Follows the target when it changes.',
|
|
217
|
+
},
|
|
218
|
+
},
|
|
219
|
+
total('scans', 'Scans'),
|
|
220
|
+
total('uniqueScanners', 'Unique scanners'),
|
|
221
|
+
total('saves', 'Saves'),
|
|
222
|
+
{
|
|
223
|
+
name: 'syncedAt',
|
|
224
|
+
label: 'Counts copied',
|
|
225
|
+
type: 'date',
|
|
226
|
+
access: { create: nobody, update: nobody },
|
|
227
|
+
admin: {
|
|
228
|
+
readOnly: true,
|
|
229
|
+
position: 'sidebar',
|
|
230
|
+
date: { pickerAppearance: 'dayAndTime' },
|
|
231
|
+
description: 'When the counts in lists were last copied from cardware.link.',
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
],
|
|
235
|
+
});
|
|
236
|
+
/** A target with links can't be deleted: printed codes would lose what they open. A manager deletes the links first. */
|
|
237
|
+
export const refuseDeleteWhileLinked = (relationTo) => async ({ id, req }) => {
|
|
238
|
+
const { totalDocs } = await req.payload.count({
|
|
239
|
+
collection: LINKS,
|
|
240
|
+
where: targetWhere(relationTo, id),
|
|
241
|
+
overrideAccess: true,
|
|
242
|
+
req,
|
|
243
|
+
});
|
|
244
|
+
if (totalDocs > 0)
|
|
245
|
+
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);
|
|
246
|
+
};
|
|
247
|
+
/**
|
|
248
|
+
* 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
|
+
*/
|
|
251
|
+
export const moveLinks = async (req, resolved, next, links) => {
|
|
252
|
+
const failed = [];
|
|
253
|
+
for (const link of links.filter((each) => each.key && each.destination !== next)) {
|
|
254
|
+
try {
|
|
255
|
+
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
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
failed.push(error instanceof Error ? error.message : String(error));
|
|
266
|
+
req.payload.logger.error({ err: error, msg: `cardware.link: link ${link.key} not moved to ${next}` });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return failed;
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Moves every link to a document whose destination no longer matches the document. Compares with each link's own
|
|
273
|
+
* copy of its destination, not the previous document, so a save after a failed move tries again (and so does the
|
|
274
|
+
* sync job). Reads the document again in full: the one a hook receives may be trimmed by the caller's `select`.
|
|
275
|
+
*/
|
|
276
|
+
export const followDestination = (resolved, collection) => async ({ doc, operation, req }) => {
|
|
277
|
+
if (operation !== 'update' || resolved.disabled)
|
|
278
|
+
return doc;
|
|
279
|
+
const { docs } = await req.payload.find({
|
|
280
|
+
collection: LINKS,
|
|
281
|
+
where: targetWhere(collection.slug, doc.id),
|
|
282
|
+
depth: 0,
|
|
283
|
+
pagination: false,
|
|
284
|
+
overrideAccess: true,
|
|
285
|
+
req,
|
|
286
|
+
});
|
|
287
|
+
const links = docs;
|
|
288
|
+
if (links.length === 0)
|
|
289
|
+
return doc;
|
|
290
|
+
const stored = await targetDoc(req, collection.slug, doc.id);
|
|
291
|
+
if (!stored)
|
|
292
|
+
return doc;
|
|
293
|
+
const next = destinationOf(collection, stored);
|
|
294
|
+
const moving = links.filter((link) => link.key && link.destination !== next);
|
|
295
|
+
const failed = await moveLinks(req, resolved, next, moving);
|
|
296
|
+
if (failed.length > 0)
|
|
297
|
+
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
|
+
return doc;
|
|
299
|
+
};
|
|
300
|
+
/**
|
|
301
|
+
* The links to a document, on the document's own screen, where a new one can be made with the target filled in.
|
|
302
|
+
* Only a signed-in reader gets them: see `withoutLinksForThePublic`.
|
|
303
|
+
*/
|
|
304
|
+
export const linksJoinField = () => ({
|
|
305
|
+
name: JOIN_FIELD,
|
|
306
|
+
label: 'Tracked links',
|
|
307
|
+
type: 'join',
|
|
308
|
+
collection: LINKS,
|
|
309
|
+
on: 'target',
|
|
310
|
+
admin: {
|
|
311
|
+
allowCreate: true,
|
|
312
|
+
defaultColumns: ['label', 'scans', 'uniqueScanners', 'saves', 'retired'],
|
|
313
|
+
},
|
|
314
|
+
});
|
|
315
|
+
/**
|
|
316
|
+
* Pages that render a document for the public read it on the server with no user, often with access overridden,
|
|
317
|
+
* and may hand the whole record to the browser. Without a user, a document comes back without its links.
|
|
318
|
+
*/
|
|
319
|
+
export const withoutLinksForThePublic = ({ doc, req }) => {
|
|
320
|
+
if (req.user || !(JOIN_FIELD in doc))
|
|
321
|
+
return doc;
|
|
322
|
+
const { [JOIN_FIELD]: _links, ...rest } = doc;
|
|
323
|
+
return rest;
|
|
324
|
+
};
|
|
@@ -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,44 @@
|
|
|
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
|
+
group?: string;
|
|
17
|
+
prefix: string;
|
|
18
|
+
collections: ResolvedCollection[];
|
|
19
|
+
/** Whether a service URL and key were given. */
|
|
20
|
+
configured: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Runs `call` with the service's client, turning a failure into an `APIError` that says what didn't happen. The
|
|
23
|
+
* client, and the key inside it, never leave this closure.
|
|
24
|
+
*/
|
|
25
|
+
service: <T>(what: string, call: (client: LinkClient) => Promise<T>) => Promise<T>;
|
|
26
|
+
callerAddress: (headers: Headers) => string;
|
|
27
|
+
sync?: {
|
|
28
|
+
cron: string;
|
|
29
|
+
queue: string;
|
|
30
|
+
autoRun: boolean;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/** Why a call to the service failed, in words for the person who asked for it. */
|
|
34
|
+
export declare const serviceFailure: (what: string, error: unknown) => APIError<any>;
|
|
35
|
+
export declare const resolve: (options: CardwareLinkOptions) => Resolved;
|
|
36
|
+
export declare const collectionOf: (resolved: Resolved, slug: string | undefined) => ResolvedCollection | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* The resolved options, kept on the server-only `config.custom` so the admin panel reads the same settings as the
|
|
39
|
+
* hooks. The service key isn't a property of it: it lives inside the `service` closure.
|
|
40
|
+
*/
|
|
41
|
+
export declare const withResolved: (custom: Record<string, unknown> | undefined, resolved: Resolved) => {
|
|
42
|
+
cardwareLink: Resolved;
|
|
43
|
+
};
|
|
44
|
+
export declare const resolvedOf: (payload: Payload) => Resolved | undefined;
|
|
@@ -0,0 +1,79 @@
|
|
|
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
|
+
group: options.admin?.group,
|
|
46
|
+
prefix,
|
|
47
|
+
collections,
|
|
48
|
+
configured: Boolean(client),
|
|
49
|
+
service: async (what, call) => {
|
|
50
|
+
if (options.disabled)
|
|
51
|
+
throw new APIError(`${what}: cardware.link is turned off on this site.`, 503);
|
|
52
|
+
if (!client)
|
|
53
|
+
throw new APIError(`${what}: cardware.link is not set up on this site (tracking.service needs a URL and a key).`, 503);
|
|
54
|
+
try {
|
|
55
|
+
return await call(client);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
throw serviceFailure(what, error);
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
callerAddress: tracking.callerAddress ?? defaultCallerAddress,
|
|
62
|
+
sync: sync && {
|
|
63
|
+
cron: sync.cron ?? '*/10 * * * *',
|
|
64
|
+
queue: sync.queue ?? SYNC_QUEUE,
|
|
65
|
+
autoRun: sync.autoRun ?? true,
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
export const collectionOf = (resolved, slug) => resolved.collections.find((collection) => collection.slug === slug);
|
|
70
|
+
const KEY = 'cardwareLink';
|
|
71
|
+
/**
|
|
72
|
+
* The resolved options, kept on the server-only `config.custom` so the admin panel reads the same settings as the
|
|
73
|
+
* hooks. The service key isn't a property of it: it lives inside the `service` closure.
|
|
74
|
+
*/
|
|
75
|
+
export const withResolved = (custom, resolved) => ({
|
|
76
|
+
...custom,
|
|
77
|
+
[KEY]: resolved,
|
|
78
|
+
});
|
|
79
|
+
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'];
|