@aglyn/aglyn 1.15.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/buy-now-pay-later.d.ts +45 -0
  3. package/src/lib/app-utils/buy-now-pay-later.js +68 -0
  4. package/src/lib/app-utils/buy-now-pay-later.js.map +1 -0
  5. package/src/lib/app-utils/contexts.d.ts +1 -0
  6. package/src/lib/app-utils/contexts.js +1 -0
  7. package/src/lib/app-utils/contexts.js.map +1 -1
  8. package/src/lib/app-utils/docs-help-sections.generated.js +2 -0
  9. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  10. package/src/lib/app-utils/docs-help.generated.d.ts +3 -3
  11. package/src/lib/app-utils/docs-help.generated.js +9 -0
  12. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  13. package/src/lib/app-utils/docs-index.generated.js +4 -4
  14. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  15. package/src/lib/app-utils/plan-entitlements.d.ts +127 -75
  16. package/src/lib/app-utils/plan-entitlements.js +120 -77
  17. package/src/lib/app-utils/plan-entitlements.js.map +1 -1
  18. package/src/lib/app-utils/plugin-bundle-checks.d.ts +14 -2
  19. package/src/lib/app-utils/plugin-bundle-checks.js +82 -7
  20. package/src/lib/app-utils/plugin-bundle-checks.js.map +1 -1
  21. package/src/lib/app-utils/plugin-connection-editor.d.ts +48 -0
  22. package/src/lib/app-utils/plugin-connection-editor.js +46 -0
  23. package/src/lib/app-utils/plugin-connection-editor.js.map +1 -0
  24. package/src/lib/app-utils/plugin-connection-record.d.ts +42 -0
  25. package/src/lib/app-utils/plugin-connection-record.js +48 -0
  26. package/src/lib/app-utils/plugin-connection-record.js.map +1 -0
  27. package/src/lib/app-utils/plugin-connection-records-context.d.ts +23 -0
  28. package/src/lib/app-utils/plugin-connection-records-context.js +29 -0
  29. package/src/lib/app-utils/plugin-connection-records-context.js.map +1 -0
  30. package/src/lib/app-utils/plugin-connection-records.d.ts +42 -0
  31. package/src/lib/app-utils/plugin-connection-records.js +56 -0
  32. package/src/lib/app-utils/plugin-connection-records.js.map +1 -0
  33. package/src/lib/app-utils/plugin-connections.d.ts +320 -0
  34. package/src/lib/app-utils/plugin-connections.js +895 -0
  35. package/src/lib/app-utils/plugin-connections.js.map +1 -0
  36. package/src/lib/app-utils/plugin-elements.d.ts +104 -0
  37. package/src/lib/app-utils/plugin-elements.js +128 -0
  38. package/src/lib/app-utils/plugin-elements.js.map +1 -0
  39. package/src/lib/app-utils/plugin-manifest.d.ts +20 -75
  40. package/src/lib/app-utils/plugin-manifest.js +65 -100
  41. package/src/lib/app-utils/plugin-manifest.js.map +1 -1
  42. package/src/lib/app-utils/realm-elements-context.d.ts +16 -0
  43. package/src/lib/app-utils/realm-elements-context.js +16 -0
  44. package/src/lib/app-utils/realm-elements-context.js.map +1 -1
  45. package/src/lib/app-utils/realm-host-surface.generated.js +1 -0
  46. package/src/lib/app-utils/realm-host-surface.generated.js.map +1 -1
  47. package/src/lib/app-utils/release-flags.d.ts +1 -1
  48. package/src/lib/app-utils/release-flags.js +11 -0
  49. package/src/lib/app-utils/release-flags.js.map +1 -1
  50. package/src/lib/app-utils/server.d.ts +1 -0
  51. package/src/lib/app-utils/server.js +2 -0
  52. package/src/lib/app-utils/server.js.map +1 -1
  53. package/src/lib/plugin-manager/feature-plugins.d.ts +25 -0
  54. package/src/lib/plugin-manager/feature-plugins.js +10 -0
  55. package/src/lib/plugin-manager/feature-plugins.js.map +1 -1
  56. package/src/lib/plugin-manager/first-party-plugins.generated.js +11 -0
  57. package/src/lib/plugin-manager/first-party-plugins.generated.js.map +1 -1
  58. package/src/lib/plugin-manager/index.d.ts +1 -0
  59. package/src/lib/plugin-manager/index.js +1 -0
  60. package/src/lib/plugin-manager/index.js.map +1 -1
  61. package/src/lib/plugin-manager/plugin-artifact-inventory.d.ts +5 -0
  62. package/src/lib/plugin-manager/plugin-artifact-inventory.js.map +1 -1
  63. package/src/lib/plugin-manager/plugin-site-csp.d.ts +36 -0
  64. package/src/lib/plugin-manager/plugin-site-csp.js +50 -1
  65. package/src/lib/plugin-manager/plugin-site-csp.js.map +1 -1
  66. package/src/lib/plugin-manager/realm-host-aglyn.generated.js +61 -59
  67. package/src/lib/plugin-manager/realm-host-aglyn.generated.js.map +1 -1
  68. package/src/lib/plugin-manager/site-page-enricher-services.d.ts +35 -0
  69. package/src/lib/plugin-manager/site-page-enricher-services.js +35 -0
  70. package/src/lib/plugin-manager/site-page-enricher-services.js.map +1 -0
  71. package/src/lib/plugin-manager/site-page-hooks.js +16 -3
  72. package/src/lib/plugin-manager/site-page-hooks.js.map +1 -1
@@ -0,0 +1,895 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * DECLARED CONNECTIONS: THE MANIFEST'S `connections` BLOCK (AGL-4193).
18
+ *
19
+ * A marketplace plugin's code runs in a sandbox, never on the platform's
20
+ * servers, so it cannot hold an OAuth grant, refresh it, or call a provider's
21
+ * API on a schedule. A connection is the plugin DECLARING all of that as data
22
+ * instead: which provider to send the site owner to, which hosts the platform
23
+ * may call with the grant, how the owner picks what to connect (an account,
24
+ * then one of its locations), and how a scheduled fetch maps the provider's
25
+ * answer into a small, typed, public record the plugin's element then reads.
26
+ * The platform runs the OAuth dance with the publisher's own OAuth app, keeps
27
+ * the tokens sealed, and makes every request itself. Third-party code never
28
+ * sees a token.
29
+ *
30
+ * Everything here is publisher-authored data that the platform turns into
31
+ * outbound requests carrying a customer's token, so it is bounded hard:
32
+ *
33
+ * - every URL is https, with no credentials, query or fragment where none
34
+ * belongs, and never an IP literal or `localhost`;
35
+ * - every request a template describes must land on a host the connection
36
+ * lists in `apiHosts`, checked again after the template is filled in;
37
+ * - a wildcard host covers exactly ONE label (`*.example.com`);
38
+ * - every list, string, page count and record has a ceiling.
39
+ *
40
+ * Pure: no Node, no Firestore, no React. The manifest validator, the bundle
41
+ * checker (and the local CLI built from it), the connect routes and the sync
42
+ * all read this one module, so a declaration cannot pass one and fail another.
43
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
44
+ /* ------------------------------------------------------------------ */ /* Bounds */ /* ------------------------------------------------------------------ */ export const PLUGIN_CONNECTION_MAX = 4;
45
+ export const PLUGIN_CONNECTION_ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
46
+ export const PLUGIN_CONNECTION_MAX_SCOPES = 20;
47
+ export const PLUGIN_CONNECTION_MAX_API_HOSTS = 10;
48
+ export const PLUGIN_CONNECTION_MAX_AUTH_PARAMS = 10;
49
+ export const PLUGIN_CONNECTION_MAX_RESOURCES = 3;
50
+ export const PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS = 200;
51
+ export const PLUGIN_CONNECTION_MAX_SYNC_REQUESTS = 3;
52
+ export const PLUGIN_CONNECTION_MAX_PAGES = 10;
53
+ export const PLUGIN_CONNECTION_MIN_INTERVAL_HOURS = 1;
54
+ export const PLUGIN_CONNECTION_MAX_INTERVAL_HOURS = 168;
55
+ export const PLUGIN_CONNECTION_MAX_RECORD_FIELDS = 20;
56
+ export const PLUGIN_CONNECTION_MAX_RECORD_ITEMS = 100;
57
+ export const PLUGIN_CONNECTION_MAX_STRING_LENGTH = 5000;
58
+ export const PLUGIN_CONNECTION_MAX_URL_LENGTH = 2048;
59
+ export const PLUGIN_CONNECTION_MAX_MAP_ENTRIES = 32;
60
+ /** The whole block, serialized: a ceiling on everything the lists above multiply to. */ export const PLUGIN_CONNECTION_MAX_DECLARATION_CHARS = 32000;
61
+ /**
62
+ * `capabilities.imageHosts`, at most (AGL-4195). Each one widens the `img-src`
63
+ * of every site that installs the plugin, so the list is kept short.
64
+ */ export const PLUGIN_MAX_IMAGE_HOSTS = 5;
65
+ const TEXT_MAX = 300;
66
+ const LABEL_MAX = 80;
67
+ const IDENTIFIER = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
68
+ const PATH_SEGMENT = /^[A-Za-z0-9_$-]{1,64}$/;
69
+ const PATH_MAX_SEGMENTS = 8;
70
+ const SCOPE = /^[!#-[\]-~]{1,200}$/;
71
+ const PARAM_NAME = /^[A-Za-z0-9_.-]{1,40}$/;
72
+ const PARAM_VALUE_MAX = 200;
73
+ const TEMPLATE_VALUE_MAX = 500;
74
+ const BODY_MAX_KEYS = 20;
75
+ const QUERY_MAX_KEYS = 10;
76
+ const HOST_LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
77
+ const PLACEHOLDER = /\{\{\s*([^{}]*?)\s*\}\}/g;
78
+ const RESOURCE_PLACEHOLDER = /^resource\.([A-Za-z][A-Za-z0-9_]{0,31})$/;
79
+ const FIELD_TYPES = [
80
+ 'string',
81
+ 'number',
82
+ 'boolean',
83
+ 'datetime',
84
+ 'url'
85
+ ];
86
+ /**
87
+ * Authorization parameters the platform sets itself. A declaration naming one
88
+ * would replace the platform's own client id, redirect, state or scope.
89
+ */ export const PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS = [
90
+ 'client_id',
91
+ 'client_secret',
92
+ 'redirect_uri',
93
+ 'response_type',
94
+ 'state',
95
+ 'scope',
96
+ 'code',
97
+ 'code_challenge',
98
+ 'code_challenge_method',
99
+ 'nonce'
100
+ ];
101
+ /* ------------------------------------------------------------------ */ /* Hosts and URLs */ /* ------------------------------------------------------------------ */ const isIpLiteral = (hostname)=>/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.includes(':') || hostname.startsWith('[');
102
+ /**
103
+ * Whether `hostname` is a usable public hostname: lowercase labels, at least two
104
+ * of them, no IP literal, no `localhost`.
105
+ */ function isPublicHostname(hostname) {
106
+ if (!hostname || hostname.length > 253 || isIpLiteral(hostname)) return false;
107
+ const labels = hostname.split('.');
108
+ if (labels.length < 2) return false;
109
+ if (labels.some((label)=>!HOST_LABEL.test(label))) return false;
110
+ const tld = labels[labels.length - 1];
111
+ if (/^\d+$/.test(tld)) return false;
112
+ return !(hostname === 'localhost' || hostname.endsWith('.localhost') || tld === 'local' || tld === 'internal');
113
+ }
114
+ /**
115
+ * A host pattern: an exact public hostname (`api.example.com`), or one whose
116
+ * first label is a lone `*` over at least two more labels (`*.example.com`).
117
+ * Anything wider — `*.com`, `*.*.example.com`, `*api.example.com` — is refused.
118
+ */ export function isPluginConnectionHostPattern(value) {
119
+ if (typeof value !== 'string') return false;
120
+ if (value !== value.toLowerCase()) return false;
121
+ if (value.startsWith('*.')) {
122
+ const rest = value.slice(2);
123
+ return !rest.includes('*') && isPublicHostname(rest) && rest.split('.').length >= 2;
124
+ }
125
+ return !value.includes('*') && isPublicHostname(value);
126
+ }
127
+ /** Whether `hostname` is covered by `pattern` (exact, or a one-label wildcard). */ export function pluginConnectionHostMatches(pattern, hostname) {
128
+ const candidate = hostname.toLowerCase();
129
+ if (!pattern.startsWith('*.')) return candidate === pattern;
130
+ const rest = pattern.slice(1) // `.example.com`
131
+ ;
132
+ if (!candidate.endsWith(rest)) return false;
133
+ const label = candidate.slice(0, candidate.length - rest.length);
134
+ return HOST_LABEL.test(label);
135
+ }
136
+ /** Whether a URL may be called with a connection's token: https, on a listed host, no credentials. */ export function isPluginConnectionUrlAllowed(url, apiHosts) {
137
+ let parsed;
138
+ try {
139
+ parsed = new URL(url);
140
+ } catch (unused) {
141
+ return false;
142
+ }
143
+ if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.port) return false;
144
+ if (parsed.hash) return false;
145
+ return apiHosts.some((pattern)=>pluginConnectionHostMatches(pattern, parsed.hostname));
146
+ }
147
+ /** An OAuth endpoint: https, a public host, no credentials, port, query or fragment. */ function endpointError(value, name) {
148
+ if (typeof value !== 'string' || !value || value.length > PLUGIN_CONNECTION_MAX_URL_LENGTH) {
149
+ return `${name} must be an https URL`;
150
+ }
151
+ let parsed;
152
+ try {
153
+ parsed = new URL(value);
154
+ } catch (unused) {
155
+ return `${name} must be an https URL`;
156
+ }
157
+ if (parsed.protocol !== 'https:') return `${name} must be an https URL`;
158
+ if (parsed.username || parsed.password || parsed.port) return `${name} must not carry credentials or a port`;
159
+ if (parsed.search || parsed.hash || value.includes('?') || value.includes('#')) {
160
+ return `${name} must not carry a query or fragment (declare authorization parameters in authParams)`;
161
+ }
162
+ if (!isPublicHostname(parsed.hostname)) return `${name} must name a public host`;
163
+ if (value.includes('{{')) return `${name} must not carry placeholders`;
164
+ return null;
165
+ }
166
+ /** The host of an endpoint URL already validated, for the bundle checker. */ export function pluginConnectionEndpointHosts(connection) {
167
+ const hosts = new Set();
168
+ for (const url of [
169
+ connection.authorizationUrl,
170
+ connection.tokenUrl,
171
+ connection.revocationUrl
172
+ ]){
173
+ if (!url) continue;
174
+ try {
175
+ hosts.add(new URL(url).hostname);
176
+ } catch (unused) {
177
+ // Validated already; nothing to add.
178
+ }
179
+ }
180
+ return [
181
+ ...hosts
182
+ ];
183
+ }
184
+ /* ------------------------------------------------------------------ */ /* Paths and templates */ /* ------------------------------------------------------------------ */ /** Whether `value` is a dot path of plain segments (`reviewer.displayName`, `items.0.id`). */ export function isPluginConnectionPath(value) {
185
+ if (typeof value !== 'string' || !value) return false;
186
+ const segments = value.split('.');
187
+ return segments.length <= PATH_MAX_SEGMENTS && segments.every((segment)=>PATH_SEGMENT.test(segment));
188
+ }
189
+ /**
190
+ * Reads a dot path out of a parsed JSON answer. Own properties only, so a
191
+ * path can never reach `__proto__` or anything else an object inherits.
192
+ */ export function readPluginConnectionPath(source, path) {
193
+ let current = source;
194
+ for (const segment of path.split('.')){
195
+ if (current === null || current === undefined) return undefined;
196
+ if (Array.isArray(current)) {
197
+ if (!/^\d+$/.test(segment)) return undefined;
198
+ current = current[Number(segment)];
199
+ continue;
200
+ }
201
+ if (typeof current !== 'object') return undefined;
202
+ if (!Object.prototype.hasOwnProperty.call(current, segment)) return undefined;
203
+ current = current[segment];
204
+ }
205
+ return current;
206
+ }
207
+ /** The resource ids a template string names, or an error for any other placeholder. */ function templateRefs(value) {
208
+ const refs = [];
209
+ for (const match of value.matchAll(PLACEHOLDER)){
210
+ var _match_;
211
+ const inner = (_match_ = match[1]) != null ? _match_ : '';
212
+ const resource = RESOURCE_PLACEHOLDER.exec(inner);
213
+ if (!resource) return {
214
+ error: `unknown placeholder "{{${inner}}}" (only {{resource.<id>}} is filled in)`
215
+ };
216
+ refs.push(resource[1]);
217
+ }
218
+ // A brace left over is a placeholder that did not parse.
219
+ const stripped = value.replace(PLACEHOLDER, '');
220
+ if (stripped.includes('{{') || stripped.includes('}}')) return {
221
+ error: 'a placeholder is not closed'
222
+ };
223
+ return {
224
+ refs
225
+ };
226
+ }
227
+ /**
228
+ * A choice a site owner made, safe to put in a URL path or query: printable,
229
+ * no `..`, nothing that could end the path or start a query, fragment,
230
+ * credential or percent-escape.
231
+ */ export function isPluginConnectionChoiceId(value) {
232
+ return typeof value === 'string' && /^[A-Za-z0-9._~:/-]{1,256}$/.test(value) && !value.split('/').some((segment)=>segment === '..' || segment === '.') && !value.startsWith('/') && !value.includes('//');
233
+ }
234
+ /**
235
+ * Fills a request template with the site's choices and the page cursor, and
236
+ * refuses a result that would leave `apiHosts`. The ONE way a template becomes
237
+ * a request: the connect routes' resource picker and the scheduled sync both
238
+ * call it, so the host check cannot be skipped by either.
239
+ */ export function preparePluginConnectionRequest(request, options) {
240
+ var _request_query;
241
+ const fill = (value)=>{
242
+ let missing = false;
243
+ const out = value.replace(PLACEHOLDER, (_whole, inner)=>{
244
+ const resource = RESOURCE_PLACEHOLDER.exec(String(inner).trim());
245
+ const choice = resource ? options.choices[resource[1]] : undefined;
246
+ if (!isPluginConnectionChoiceId(choice)) {
247
+ missing = true;
248
+ return '';
249
+ }
250
+ return choice;
251
+ });
252
+ return missing ? null : out;
253
+ };
254
+ const url = fill(request.url);
255
+ if (url === null) return {
256
+ ok: false,
257
+ error: 'a choice this request needs has not been made'
258
+ };
259
+ let parsed;
260
+ try {
261
+ parsed = new URL(url);
262
+ } catch (unused) {
263
+ return {
264
+ ok: false,
265
+ error: 'the request URL is not valid'
266
+ };
267
+ }
268
+ for (const [key, value] of Object.entries((_request_query = request.query) != null ? _request_query : {})){
269
+ const filled = fill(value);
270
+ if (filled === null) return {
271
+ ok: false,
272
+ error: 'a choice this request needs has not been made'
273
+ };
274
+ parsed.searchParams.set(key, filled);
275
+ }
276
+ if (options.cursor && request.pagination) {
277
+ parsed.searchParams.set(request.pagination.cursorParam, options.cursor);
278
+ }
279
+ const finalUrl = parsed.toString();
280
+ if (!isPluginConnectionUrlAllowed(finalUrl, options.apiHosts)) {
281
+ return {
282
+ ok: false,
283
+ error: 'the request would leave the connection’s declared hosts'
284
+ };
285
+ }
286
+ if (request.method === 'GET' || !request.body) {
287
+ return {
288
+ ok: true,
289
+ request: {
290
+ method: request.method,
291
+ url: finalUrl
292
+ }
293
+ };
294
+ }
295
+ const body = {};
296
+ for (const [key, value] of Object.entries(request.body)){
297
+ if (typeof value !== 'string') {
298
+ body[key] = value;
299
+ continue;
300
+ }
301
+ const filled = fill(value);
302
+ if (filled === null) return {
303
+ ok: false,
304
+ error: 'a choice this request needs has not been made'
305
+ };
306
+ body[key] = filled;
307
+ }
308
+ return {
309
+ ok: true,
310
+ request: {
311
+ method: request.method,
312
+ url: finalUrl,
313
+ body: JSON.stringify(body)
314
+ }
315
+ };
316
+ }
317
+ const fail = (error)=>({
318
+ ok: false,
319
+ error
320
+ });
321
+ const isRecord = (value)=>!!value && typeof value === 'object' && !Array.isArray(value);
322
+ const boundedText = (value, max)=>typeof value === 'string' && value.trim() && value.trim().length <= max ? value.trim() : null;
323
+ const intIn = (value, min, max)=>typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max ? value : null;
324
+ /** The host part of a template URL, before any placeholder could appear. */ function templateUrlError(url, apiHosts, where) {
325
+ if (typeof url !== 'string' || !url || url.length > PLUGIN_CONNECTION_MAX_URL_LENGTH) {
326
+ return `${where}: url must be an https URL`;
327
+ }
328
+ const authorityEnd = url.indexOf('/', 'https://'.length);
329
+ const head = authorityEnd === -1 ? url : url.slice(0, authorityEnd);
330
+ if (!url.startsWith('https://')) return `${where}: url must be an https URL`;
331
+ if (head.includes('{{') || head.includes('@')) return `${where}: url must name its host literally`;
332
+ if (url.includes('#')) return `${where}: url must not carry a fragment`;
333
+ // Placeholders replaced with a harmless id to judge the URL's shape.
334
+ const probe = url.replace(PLACEHOLDER, 'x');
335
+ if (!isPluginConnectionUrlAllowed(probe, apiHosts)) {
336
+ return `${where}: url must be on one of the connection's apiHosts`;
337
+ }
338
+ return null;
339
+ }
340
+ function validatePagination(raw, where) {
341
+ if (raw === undefined) return {
342
+ ok: true,
343
+ value: undefined
344
+ };
345
+ if (!isRecord(raw)) return fail(`${where}: pagination must be an object`);
346
+ if (!isPluginConnectionPath(raw['cursorPath'])) return fail(`${where}: pagination.cursorPath must be a dot path`);
347
+ if (typeof raw['cursorParam'] !== 'string' || !PARAM_NAME.test(raw['cursorParam'])) {
348
+ return fail(`${where}: pagination.cursorParam must be a query parameter name`);
349
+ }
350
+ const maxPages = intIn(raw['maxPages'], 1, PLUGIN_CONNECTION_MAX_PAGES);
351
+ if (maxPages === null) {
352
+ return fail(`${where}: pagination.maxPages must be a whole number from 1 to ${PLUGIN_CONNECTION_MAX_PAGES}`);
353
+ }
354
+ return {
355
+ ok: true,
356
+ value: {
357
+ cursorPath: raw['cursorPath'],
358
+ cursorParam: raw['cursorParam'],
359
+ maxPages
360
+ }
361
+ };
362
+ }
363
+ function validateRequest(raw, where, context) {
364
+ var _raw_method;
365
+ if (!isRecord(raw)) return fail(`${where} must be an object`);
366
+ const method = (_raw_method = raw['method']) != null ? _raw_method : 'GET';
367
+ if (method !== 'GET' && method !== 'POST') return fail(`${where}: method must be GET or POST`);
368
+ const urlError = templateUrlError(raw['url'], context.apiHosts, where);
369
+ if (urlError) return fail(urlError);
370
+ const url = raw['url'];
371
+ const refs = [];
372
+ const collect = (value, label)=>{
373
+ if (value.length > TEMPLATE_VALUE_MAX && label !== 'url') return `${where}: ${label} is too long`;
374
+ const parsed = templateRefs(value);
375
+ if ('error' in parsed) return `${where}: ${label} has an ${parsed.error}`;
376
+ refs.push(...parsed.refs);
377
+ return null;
378
+ };
379
+ const urlRefs = collect(url, 'url');
380
+ if (urlRefs) return fail(urlRefs);
381
+ let query;
382
+ if (raw['query'] !== undefined) {
383
+ if (!isRecord(raw['query'])) return fail(`${where}: query must be an object of strings`);
384
+ const entries = Object.entries(raw['query']);
385
+ if (entries.length > QUERY_MAX_KEYS) return fail(`${where}: query names too many parameters`);
386
+ query = {};
387
+ for (const [key, value] of entries){
388
+ if (!PARAM_NAME.test(key) || typeof value !== 'string') {
389
+ return fail(`${where}: query must be an object of strings`);
390
+ }
391
+ const error = collect(value, `query.${key}`);
392
+ if (error) return fail(error);
393
+ query[key] = value;
394
+ }
395
+ }
396
+ let body;
397
+ if (raw['body'] !== undefined) {
398
+ if (method !== 'POST') return fail(`${where}: only a POST request has a body`);
399
+ if (!isRecord(raw['body'])) return fail(`${where}: body must be a flat object`);
400
+ const entries = Object.entries(raw['body']);
401
+ if (entries.length > BODY_MAX_KEYS) return fail(`${where}: body has too many fields`);
402
+ body = {};
403
+ for (const [key, value] of entries){
404
+ if (!PARAM_NAME.test(key)) return fail(`${where}: body field "${key}" is not a plain name`);
405
+ if (typeof value === 'string') {
406
+ const error = collect(value, `body.${key}`);
407
+ if (error) return fail(error);
408
+ body[key] = value;
409
+ } else if (typeof value === 'number' && Number.isFinite(value)) {
410
+ body[key] = value;
411
+ } else if (typeof value === 'boolean') {
412
+ body[key] = value;
413
+ } else {
414
+ return fail(`${where}: body must be a flat object of strings, numbers and booleans`);
415
+ }
416
+ }
417
+ }
418
+ for (const ref of refs){
419
+ if (!context.resourceIds.includes(ref)) {
420
+ return fail(`${where}: {{resource.${ref}}} names no resource declared before it`);
421
+ }
422
+ }
423
+ let itemsPath;
424
+ if (raw['itemsPath'] !== undefined) {
425
+ if (!isPluginConnectionPath(raw['itemsPath'])) return fail(`${where}: itemsPath must be a dot path`);
426
+ itemsPath = raw['itemsPath'];
427
+ } else if (context.requireItems) {
428
+ return fail(`${where}: itemsPath is required`);
429
+ }
430
+ const pagination = validatePagination(raw['pagination'], where);
431
+ if (pagination.ok === false) return pagination;
432
+ if (pagination.value && !itemsPath) return fail(`${where}: a paginated request needs an itemsPath`);
433
+ return {
434
+ ok: true,
435
+ value: _extends({
436
+ method,
437
+ url
438
+ }, query && Object.keys(query).length ? {
439
+ query
440
+ } : {}, body ? {
441
+ body
442
+ } : {}, itemsPath ? {
443
+ itemsPath
444
+ } : {}, pagination.value ? {
445
+ pagination: pagination.value
446
+ } : {})
447
+ };
448
+ }
449
+ function validateField(raw, where) {
450
+ if (!isRecord(raw)) return fail(`${where} must be an object`);
451
+ const type = raw['type'];
452
+ if (!FIELD_TYPES.includes(type)) {
453
+ return fail(`${where}: type must be one of ${FIELD_TYPES.join(', ')}`);
454
+ }
455
+ if (!isPluginConnectionPath(raw['path'])) return fail(`${where}: path must be a dot path`);
456
+ const field = {
457
+ type: type,
458
+ path: raw['path']
459
+ };
460
+ if (type === 'string' || type === 'url') {
461
+ const ceiling = type === 'url' ? PLUGIN_CONNECTION_MAX_URL_LENGTH : PLUGIN_CONNECTION_MAX_STRING_LENGTH;
462
+ const maxLength = intIn(raw['maxLength'], 1, ceiling);
463
+ if (maxLength === null) return fail(`${where}: maxLength is required, a whole number from 1 to ${ceiling}`);
464
+ field.maxLength = maxLength;
465
+ } else if (raw['maxLength'] !== undefined) {
466
+ return fail(`${where}: only a string or url field has a maxLength`);
467
+ }
468
+ if (raw['map'] !== undefined) {
469
+ if (!isRecord(raw['map'])) return fail(`${where}: map must be an object`);
470
+ const entries = Object.entries(raw['map']);
471
+ if (!entries.length || entries.length > PLUGIN_CONNECTION_MAX_MAP_ENTRIES) {
472
+ return fail(`${where}: map must have 1 to ${PLUGIN_CONNECTION_MAX_MAP_ENTRIES} entries`);
473
+ }
474
+ const map = {};
475
+ for (const [key, value] of entries){
476
+ if (key.length > 100) return fail(`${where}: a map key is too long`);
477
+ if (typeof value === 'string' && value.length <= 200) map[key] = value;
478
+ else if (typeof value === 'number' && Number.isFinite(value)) map[key] = value;
479
+ else if (typeof value === 'boolean') map[key] = value;
480
+ else return fail(`${where}: map values must be short strings, numbers or booleans`);
481
+ }
482
+ field.map = map;
483
+ }
484
+ return {
485
+ ok: true,
486
+ value: field
487
+ };
488
+ }
489
+ function validateFieldSet(raw, where, each, required) {
490
+ if (raw === undefined) return required ? fail(`${where} is required`) : {
491
+ ok: true,
492
+ value: undefined
493
+ };
494
+ if (!isRecord(raw)) return fail(`${where} must be an object`);
495
+ const entries = Object.entries(raw);
496
+ if (required && !entries.length || entries.length > PLUGIN_CONNECTION_MAX_RECORD_FIELDS) {
497
+ return fail(`${where} must name 1 to ${PLUGIN_CONNECTION_MAX_RECORD_FIELDS} fields`);
498
+ }
499
+ const out = {};
500
+ for (const [name, value] of entries){
501
+ if (!IDENTIFIER.test(name)) return fail(`${where}: "${name}" is not a plain field name`);
502
+ const verdict = each(value, `${where}.${name}`);
503
+ if (verdict.ok === false) return verdict;
504
+ out[name] = verdict.value;
505
+ }
506
+ return {
507
+ ok: true,
508
+ value: out
509
+ };
510
+ }
511
+ function validateSync(raw, where, context) {
512
+ if (raw === undefined) return {
513
+ ok: true,
514
+ value: undefined
515
+ };
516
+ if (!isRecord(raw)) return fail(`${where} must be an object`);
517
+ const intervalHours = intIn(raw['intervalHours'], PLUGIN_CONNECTION_MIN_INTERVAL_HOURS, PLUGIN_CONNECTION_MAX_INTERVAL_HOURS);
518
+ if (intervalHours === null) {
519
+ return fail(`${where}: intervalHours must be a whole number from ${PLUGIN_CONNECTION_MIN_INTERVAL_HOURS} to ${PLUGIN_CONNECTION_MAX_INTERVAL_HOURS}`);
520
+ }
521
+ const requestsRaw = raw['requests'];
522
+ if (!Array.isArray(requestsRaw) || !requestsRaw.length || requestsRaw.length > PLUGIN_CONNECTION_MAX_SYNC_REQUESTS) {
523
+ return fail(`${where}: requests must list 1 to ${PLUGIN_CONNECTION_MAX_SYNC_REQUESTS} requests`);
524
+ }
525
+ const requests = [];
526
+ for (const [index, entry] of requestsRaw.entries()){
527
+ const at = `${where}.requests[${index}]`;
528
+ if (!isRecord(entry) || typeof entry['id'] !== 'string' || !IDENTIFIER.test(entry['id'])) {
529
+ return fail(`${at}: id must be a plain identifier`);
530
+ }
531
+ if (requests.some((request)=>request.id === entry['id'])) return fail(`${at}: id "${entry['id']}" is used twice`);
532
+ const verdict = validateRequest(entry, at, _extends({}, context, {
533
+ requireItems: false
534
+ }));
535
+ if (verdict.ok === false) return verdict;
536
+ requests.push(_extends({
537
+ id: entry['id']
538
+ }, verdict.value));
539
+ }
540
+ const recordRaw = raw['record'];
541
+ if (!isRecord(recordRaw)) return fail(`${where}: record must be an object`);
542
+ const requestIds = requests.map((request)=>request.id);
543
+ const fields = validateFieldSet(recordRaw['fields'], `${where}.record.fields`, (value, at)=>{
544
+ if (!isRecord(value) || typeof value['request'] !== 'string' || !requestIds.includes(value['request'])) {
545
+ return fail(`${at}: request must name one of the sync requests`);
546
+ }
547
+ const field = validateField(value, at);
548
+ if (field.ok === false) return field;
549
+ return {
550
+ ok: true,
551
+ value: _extends({
552
+ request: value['request']
553
+ }, field.value)
554
+ };
555
+ }, false);
556
+ if (fields.ok === false) return fields;
557
+ let items;
558
+ if (recordRaw['items'] !== undefined) {
559
+ var _itemFields_value;
560
+ const itemsRaw = recordRaw['items'];
561
+ const at = `${where}.record.items`;
562
+ if (!isRecord(itemsRaw)) return fail(`${at} must be an object`);
563
+ const source = requests.find((request)=>request.id === itemsRaw['request']);
564
+ if (!source) return fail(`${at}: request must name one of the sync requests`);
565
+ if (!source.itemsPath) return fail(`${at}: request "${source.id}" declares no itemsPath`);
566
+ const maxItems = intIn(itemsRaw['maxItems'], 1, PLUGIN_CONNECTION_MAX_RECORD_ITEMS);
567
+ if (maxItems === null) return fail(`${at}: maxItems must be a whole number from 1 to ${PLUGIN_CONNECTION_MAX_RECORD_ITEMS}`);
568
+ const itemFields = validateFieldSet(itemsRaw['fields'], `${at}.fields`, validateField, true);
569
+ if (itemFields.ok === false) return itemFields;
570
+ items = {
571
+ request: source.id,
572
+ maxItems,
573
+ fields: (_itemFields_value = itemFields.value) != null ? _itemFields_value : {}
574
+ };
575
+ }
576
+ if (!fields.value && !items) return fail(`${where}: record must declare fields, items or both`);
577
+ return {
578
+ ok: true,
579
+ value: {
580
+ intervalHours,
581
+ requests,
582
+ record: _extends({}, fields.value ? {
583
+ fields: fields.value
584
+ } : {}, items ? {
585
+ items
586
+ } : {})
587
+ }
588
+ };
589
+ }
590
+ /** Validates one connection. */ export function validatePluginConnection(raw, where = 'connection') {
591
+ if (!isRecord(raw)) return fail(`${where} must be an object`);
592
+ const id = raw['id'];
593
+ if (typeof id !== 'string' || !PLUGIN_CONNECTION_ID_PATTERN.test(id)) {
594
+ return fail(`${where}: id must be lowercase letters, digits and dashes (2 to 32)`);
595
+ }
596
+ const at = `connection "${id}"`;
597
+ const provider = raw['provider'];
598
+ if (typeof provider !== 'string' || !PLUGIN_CONNECTION_ID_PATTERN.test(provider)) {
599
+ return fail(`${at}: provider must be lowercase letters, digits and dashes (2 to 32)`);
600
+ }
601
+ const label = boundedText(raw['label'], LABEL_MAX);
602
+ if (!label) return fail(`${at}: label is required (at most ${LABEL_MAX} characters)`);
603
+ let description;
604
+ if (raw['description'] !== undefined) {
605
+ const text = boundedText(raw['description'], TEXT_MAX);
606
+ if (!text) return fail(`${at}: description must be at most ${TEXT_MAX} characters`);
607
+ description = text;
608
+ }
609
+ for (const name of [
610
+ 'authorizationUrl',
611
+ 'tokenUrl'
612
+ ]){
613
+ const error = endpointError(raw[name], name);
614
+ if (error) return fail(`${at}: ${error}`);
615
+ }
616
+ if (raw['revocationUrl'] !== undefined) {
617
+ const error = endpointError(raw['revocationUrl'], 'revocationUrl');
618
+ if (error) return fail(`${at}: ${error}`);
619
+ }
620
+ const scopesRaw = raw['scopes'];
621
+ if (!Array.isArray(scopesRaw) || !scopesRaw.length || scopesRaw.length > PLUGIN_CONNECTION_MAX_SCOPES) {
622
+ return fail(`${at}: scopes must list 1 to ${PLUGIN_CONNECTION_MAX_SCOPES} scopes`);
623
+ }
624
+ if (scopesRaw.some((scope)=>typeof scope !== 'string' || !SCOPE.test(scope) || scope.includes(','))) {
625
+ return fail(`${at}: a scope must be printable, with no spaces or commas`);
626
+ }
627
+ const scopeSeparator = raw['scopeSeparator'];
628
+ if (scopeSeparator !== undefined && scopeSeparator !== ' ' && scopeSeparator !== ',') {
629
+ return fail(`${at}: scopeSeparator must be a space or a comma`);
630
+ }
631
+ let authParams;
632
+ if (raw['authParams'] !== undefined) {
633
+ if (!isRecord(raw['authParams'])) return fail(`${at}: authParams must be an object of strings`);
634
+ const entries = Object.entries(raw['authParams']);
635
+ if (entries.length > PLUGIN_CONNECTION_MAX_AUTH_PARAMS) return fail(`${at}: authParams names too many parameters`);
636
+ authParams = {};
637
+ for (const [key, value] of entries){
638
+ if (!PARAM_NAME.test(key) || typeof value !== 'string' || value.length > PARAM_VALUE_MAX) {
639
+ return fail(`${at}: authParams must be an object of short strings`);
640
+ }
641
+ if (PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS.includes(key.toLowerCase())) {
642
+ return fail(`${at}: authParams may not set "${key}", which the platform sets itself`);
643
+ }
644
+ authParams[key] = value;
645
+ }
646
+ }
647
+ const tokenAuthMethod = raw['tokenAuthMethod'];
648
+ if (tokenAuthMethod !== undefined && tokenAuthMethod !== 'body' && tokenAuthMethod !== 'basic') {
649
+ return fail(`${at}: tokenAuthMethod must be "body" or "basic"`);
650
+ }
651
+ const apiHostsRaw = raw['apiHosts'];
652
+ if (!Array.isArray(apiHostsRaw) || !apiHostsRaw.length || apiHostsRaw.length > PLUGIN_CONNECTION_MAX_API_HOSTS) {
653
+ return fail(`${at}: apiHosts must list 1 to ${PLUGIN_CONNECTION_MAX_API_HOSTS} hosts`);
654
+ }
655
+ for (const pattern of apiHostsRaw){
656
+ if (!isPluginConnectionHostPattern(pattern)) {
657
+ return fail(`${at}: api host "${String(pattern)}" must be a lowercase public hostname, or *.<domain> with one wildcard label`);
658
+ }
659
+ }
660
+ const apiHosts = [
661
+ ...new Set(apiHostsRaw)
662
+ ];
663
+ const resources = [];
664
+ if (raw['resources'] !== undefined) {
665
+ const list = raw['resources'];
666
+ if (!Array.isArray(list) || list.length > PLUGIN_CONNECTION_MAX_RESOURCES) {
667
+ return fail(`${at}: resources must list at most ${PLUGIN_CONNECTION_MAX_RESOURCES} resources`);
668
+ }
669
+ for (const [index, entry] of list.entries()){
670
+ const where2 = `${at} resources[${index}]`;
671
+ if (!isRecord(entry) || typeof entry['id'] !== 'string' || !IDENTIFIER.test(entry['id'])) {
672
+ return fail(`${where2}: id must be a plain identifier`);
673
+ }
674
+ const resourceId = entry['id'];
675
+ if (resources.some((resource)=>resource.id === resourceId)) return fail(`${where2}: id "${resourceId}" is used twice`);
676
+ const resourceLabel = boundedText(entry['label'], LABEL_MAX);
677
+ if (!resourceLabel) return fail(`${where2}: label is required (at most ${LABEL_MAX} characters)`);
678
+ const request = validateRequest(entry['request'], `${where2}.request`, {
679
+ apiHosts,
680
+ resourceIds: resources.map((resource)=>resource.id),
681
+ requireItems: true
682
+ });
683
+ if (request.ok === false) return request;
684
+ if (!isPluginConnectionPath(entry['idPath'])) return fail(`${where2}: idPath must be a dot path`);
685
+ if (!isPluginConnectionPath(entry['labelPath'])) return fail(`${where2}: labelPath must be a dot path`);
686
+ const maxItems = entry['maxItems'] === undefined ? 100 : intIn(entry['maxItems'], 1, PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS);
687
+ if (maxItems === null) {
688
+ return fail(`${where2}: maxItems must be a whole number from 1 to ${PLUGIN_CONNECTION_MAX_RESOURCE_ITEMS}`);
689
+ }
690
+ resources.push({
691
+ id: resourceId,
692
+ label: resourceLabel,
693
+ request: request.value,
694
+ idPath: entry['idPath'],
695
+ labelPath: entry['labelPath'],
696
+ maxItems
697
+ });
698
+ }
699
+ }
700
+ const sync = validateSync(raw['sync'], `${at} sync`, {
701
+ apiHosts,
702
+ resourceIds: resources.map((resource)=>resource.id)
703
+ });
704
+ if (sync.ok === false) return sync;
705
+ return {
706
+ ok: true,
707
+ value: _extends({
708
+ id,
709
+ provider,
710
+ label
711
+ }, description ? {
712
+ description
713
+ } : {}, {
714
+ authorizationUrl: raw['authorizationUrl'],
715
+ tokenUrl: raw['tokenUrl']
716
+ }, raw['revocationUrl'] !== undefined ? {
717
+ revocationUrl: raw['revocationUrl']
718
+ } : {}, {
719
+ scopes: [
720
+ ...new Set(scopesRaw)
721
+ ]
722
+ }, scopeSeparator ? {
723
+ scopeSeparator: scopeSeparator
724
+ } : {}, authParams && Object.keys(authParams).length ? {
725
+ authParams
726
+ } : {}, tokenAuthMethod ? {
727
+ tokenAuthMethod: tokenAuthMethod
728
+ } : {}, {
729
+ apiHosts
730
+ }, resources.length ? {
731
+ resources
732
+ } : {}, sync.value ? {
733
+ sync: sync.value
734
+ } : {})
735
+ };
736
+ }
737
+ /**
738
+ * Validates a manifest's whole `connections` block. Refused whole when any
739
+ * entry is malformed — unlike an element, a connection dropped on the way in
740
+ * is an OAuth flow and a sync that silently do not exist.
741
+ */ export function validatePluginConnections(raw) {
742
+ if (raw === undefined || raw === null) return {
743
+ ok: true,
744
+ value: []
745
+ };
746
+ if (!Array.isArray(raw)) return fail('connections must be a list');
747
+ if (raw.length > PLUGIN_CONNECTION_MAX) return fail(`At most ${PLUGIN_CONNECTION_MAX} connections may be declared`);
748
+ let serialized;
749
+ try {
750
+ serialized = JSON.stringify(raw);
751
+ } catch (unused) {
752
+ return fail('connections must be plain JSON');
753
+ }
754
+ if (serialized.length > PLUGIN_CONNECTION_MAX_DECLARATION_CHARS) {
755
+ return fail(`connections must serialize to at most ${PLUGIN_CONNECTION_MAX_DECLARATION_CHARS} characters`);
756
+ }
757
+ const out = [];
758
+ for (const [index, entry] of raw.entries()){
759
+ const verdict = validatePluginConnection(entry, `connections[${index}]`);
760
+ if (verdict.ok === false) return verdict;
761
+ if (out.some((connection)=>connection.id === verdict.value.id)) {
762
+ return fail(`connection id "${verdict.value.id}" is declared twice`);
763
+ }
764
+ out.push(verdict.value);
765
+ }
766
+ return {
767
+ ok: true,
768
+ value: out
769
+ };
770
+ }
771
+ /**
772
+ * Validates `capabilities.imageHosts`: the hosts a plugin's element may show
773
+ * images from on a published site. The tenant admits each, as an `https://`
774
+ * source, to the `img-src` of the sites that install the plugin (AGL-4195),
775
+ * so the rule is strict: a bare lowercase public hostname, or `*.` over one
776
+ * label of a domain (never `*.com`), no scheme (so never `data:` or `http:`),
777
+ * no port, no path, at most {@link PLUGIN_MAX_IMAGE_HOSTS}. Same host rule as
778
+ * `apiHosts`.
779
+ */ export function validatePluginImageHosts(raw) {
780
+ if (raw === undefined) return {
781
+ ok: true,
782
+ value: []
783
+ };
784
+ if (!Array.isArray(raw) || raw.length > PLUGIN_MAX_IMAGE_HOSTS) {
785
+ return fail(`imageHosts must list at most ${PLUGIN_MAX_IMAGE_HOSTS} hosts`);
786
+ }
787
+ for (const pattern of raw){
788
+ if (!isPluginConnectionHostPattern(pattern)) {
789
+ return fail(`Image host "${String(pattern)}" must be a lowercase public hostname, or *.<domain> with one wildcard label`);
790
+ }
791
+ }
792
+ return {
793
+ ok: true,
794
+ value: [
795
+ ...new Set(raw)
796
+ ]
797
+ };
798
+ }
799
+ /** The connection a manifest declares under `connectionId`, re-validated, or `null`. */ export function findPluginConnection(manifest, connectionId) {
800
+ var _verdict_value_find;
801
+ const verdict = validatePluginConnections(manifest == null ? void 0 : manifest.connections);
802
+ if (verdict.ok === false) return null;
803
+ return (_verdict_value_find = verdict.value.find((connection)=>connection.id === connectionId)) != null ? _verdict_value_find : null;
804
+ }
805
+ /**
806
+ * The authorization address the site owner is sent to: the declared
807
+ * endpoint with the platform's own client id, redirect, state and scope, and
808
+ * the declaration's extra parameters, which may not override any of those.
809
+ */ export function pluginConnectionAuthorizeUrl(connection, options) {
810
+ var _connection_authParams, _connection_scopeSeparator;
811
+ const url = new URL(connection.authorizationUrl);
812
+ for (const [key, value] of Object.entries((_connection_authParams = connection.authParams) != null ? _connection_authParams : {})){
813
+ if (PLUGIN_CONNECTION_RESERVED_AUTH_PARAMS.includes(key.toLowerCase())) continue;
814
+ url.searchParams.set(key, value);
815
+ }
816
+ url.searchParams.set('response_type', 'code');
817
+ url.searchParams.set('client_id', options.clientId);
818
+ url.searchParams.set('redirect_uri', options.redirectUri);
819
+ url.searchParams.set('scope', connection.scopes.join((_connection_scopeSeparator = connection.scopeSeparator) != null ? _connection_scopeSeparator : ' '));
820
+ url.searchParams.set('state', options.state);
821
+ return url.toString();
822
+ }
823
+ /* ------------------------------------------------------------------ */ /* Site variables from a record (AGL-4195) */ /* ------------------------------------------------------------------ */ /** The longest id a `{{var:…}}` token carries (`binding-tokens.ts`). */ const VARIABLE_ID_MAX = 64;
824
+ const VARIABLE_ID_REF = /^[A-Za-z0-9_-]{1,64}$/;
825
+ /**
826
+ * The `{{var:…}}` id a record's SUMMARY field resolves under on a site:
827
+ * `{listingId}__{connectionId}-{field}`, e.g. `Kq3…__reviews-rating`.
828
+ *
829
+ * Chosen so it can never be a site's own variable and can never be two
830
+ * fields at once:
831
+ *
832
+ * - a site's own variables carry Firestore auto ids (letters and digits),
833
+ * and this id always holds `__` and `-`;
834
+ * - a field name never holds `-` (`[A-Za-z][A-Za-z0-9_]*`), so the field is
835
+ * what follows the LAST `-`; a connection id never holds `_`, so the
836
+ * connection is what follows the last `__` before it, and the listing is
837
+ * the rest. Two different triples therefore never spell the same id.
838
+ *
839
+ * `null` when the id would not fit a token (64 characters): such a field
840
+ * has no variable, rather than one that no token could name.
841
+ */ export function pluginConnectionVariableId(listingId, connectionId, field) {
842
+ if (!PLUGIN_CONNECTION_ID_PATTERN.test(connectionId) || !IDENTIFIER.test(field)) return null;
843
+ const id = `${listingId}__${connectionId}-${field}`;
844
+ return id.length <= VARIABLE_ID_MAX && VARIABLE_ID_REF.test(id) ? id : null;
845
+ }
846
+ /** How a record value of each declared type is held as a site variable. */ const VARIABLE_TYPE_OF = {
847
+ string: 'text',
848
+ url: 'text',
849
+ number: 'number',
850
+ boolean: 'boolean',
851
+ datetime: 'date'
852
+ };
853
+ /**
854
+ * The site variables one connection's record gives a site: one per declared
855
+ * SUMMARY field (`sync.record.fields`) holding a value, under
856
+ * {@link pluginConnectionVariableId}. A field the record does not hold, or
857
+ * holds as a value of another type than declared, has no variable, so its
858
+ * token renders empty as any unknown variable does. Items never become
859
+ * variables: a list has no single value to print.
860
+ *
861
+ * Each variable's `name` is its id. Names are what a function's expressions
862
+ * read, and an id with `-` in it is not a name an expression can spell, so
863
+ * these never shadow one of the site's own variables in a function.
864
+ */ export function pluginConnectionRecordVariables(listingId, connection, fields) {
865
+ var _ref;
866
+ var _connection_sync;
867
+ const out = {};
868
+ const declared = (_ref = (_connection_sync = connection.sync) == null ? void 0 : _connection_sync.record.fields) != null ? _ref : {};
869
+ for (const [field, declaration] of Object.entries(declared)){
870
+ const value = fields == null ? void 0 : fields[field];
871
+ const id = pluginConnectionVariableId(listingId, connection.id, field);
872
+ if (!id || value === null || value === undefined) continue;
873
+ const type = VARIABLE_TYPE_OF[declaration.type];
874
+ let stored = null;
875
+ if (declaration.type === 'number' && typeof value === 'number' && Number.isFinite(value)) {
876
+ stored = String(value);
877
+ } else if (declaration.type === 'boolean' && typeof value === 'boolean') {
878
+ stored = value ? 'true' : 'false';
879
+ } else if (declaration.type === 'datetime' && typeof value === 'number' && Number.isFinite(value)) {
880
+ const date = new Date(value);
881
+ stored = Number.isNaN(date.getTime()) ? null : date.toISOString();
882
+ } else if ((declaration.type === 'string' || declaration.type === 'url') && typeof value === 'string') {
883
+ stored = value;
884
+ }
885
+ if (stored === null) continue;
886
+ out[id] = {
887
+ name: id,
888
+ type,
889
+ value: stored
890
+ };
891
+ }
892
+ return out;
893
+ }
894
+
895
+ //# sourceMappingURL=plugin-connections.js.map