@occluze/tether 0.7.0 → 0.7.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 (132) hide show
  1. package/README.md +21 -21
  2. package/dist/esm/chunks/{account-UIPWJQ3Y.js → account-CXMA5RPZ.js} +1 -1
  3. package/dist/esm/chunks/{account-pages-6ROA6Y4V.js → account-pages-IZO7FEOZ.js} +1 -1
  4. package/dist/esm/chunks/{analytics-2V632IRV.js → analytics-PG5FPRDN.js} +1 -1
  5. package/dist/esm/chunks/{chunk-4GCXM764.js → chunk-4HD4J5JC.js} +1 -1
  6. package/dist/esm/chunks/{chunk-BFTZR4OB.js → chunk-6TFMLT4A.js} +2 -2
  7. package/dist/esm/chunks/{chunk-T44MUL4Y.js → chunk-BBVUVPMO.js} +1 -1
  8. package/dist/esm/chunks/chunk-EW5SYO6L.js +1 -0
  9. package/dist/esm/chunks/chunk-HJY2JSNB.js +1 -0
  10. package/dist/esm/chunks/chunk-MQYB6BH4.js +1 -0
  11. package/dist/esm/chunks/{chunk-5Z5O3767.js → chunk-N3V45JPS.js} +1 -1
  12. package/dist/esm/chunks/{chunk-YLUULATY.js → chunk-RPMBCAGS.js} +1 -1
  13. package/dist/esm/chunks/{chunk-MPDWM2NN.js → chunk-VFNHIGCS.js} +1 -1
  14. package/dist/esm/chunks/{chunk-6OZJCAGZ.js → chunk-WT7RGGJU.js} +1 -1
  15. package/dist/esm/chunks/chunk-YN6LEBEN.js +1 -0
  16. package/dist/esm/chunks/chunk-Z6HS3H7K.js +1 -0
  17. package/dist/esm/chunks/{diagnose-3FEKRIEK.js → diagnose-XCEBQKBO.js} +1 -1
  18. package/dist/esm/chunks/extras-4HU3VSBQ.js +1 -0
  19. package/dist/esm/chunks/{markets-ui-FD6NI2OG.js → markets-ui-M4IQ62CT.js} +1 -1
  20. package/dist/esm/chunks/search-A5DS2IOS.js +1 -0
  21. package/dist/esm/index.js +1 -1
  22. package/dist/esm/server.js +2 -2
  23. package/dist/tether.account-pages.js +13 -3
  24. package/dist/tether.account-pages.min.js +1 -1
  25. package/dist/tether.account.js +13 -3
  26. package/dist/tether.account.min.js +1 -1
  27. package/dist/tether.analytics.js +18 -3
  28. package/dist/tether.analytics.min.js +1 -1
  29. package/dist/tether.diagnose.js +18 -3
  30. package/dist/tether.diagnose.min.js +2 -2
  31. package/dist/tether.extras.js +19 -6
  32. package/dist/tether.extras.min.js +1 -1
  33. package/dist/tether.js +162 -112
  34. package/dist/tether.markets.js +18 -3
  35. package/dist/tether.markets.min.js +1 -1
  36. package/dist/tether.min.js +3 -3
  37. package/dist/tether.min.js.map +4 -4
  38. package/dist/tether.search.js +18 -3
  39. package/dist/tether.search.min.js +1 -1
  40. package/dist/types/server/src/shared/cart-id.d.ts +2 -0
  41. package/dist/types/src/cart/mutations.d.ts +6 -0
  42. package/dist/types/src/cart/store.d.ts +5 -2
  43. package/dist/types/src/cart.d.ts +2 -2
  44. package/dist/types/src/client.d.ts +53 -19
  45. package/dist/types/src/config.d.ts +6 -1
  46. package/dist/types/src/index.d.ts +2 -2
  47. package/dist/types/src/product-shape.d.ts +3 -1
  48. package/package.json +1 -2
  49. package/dist/esm/chunks/chunk-56FCLJJD.js +0 -1
  50. package/dist/esm/chunks/chunk-A5SYCVQM.js +0 -1
  51. package/dist/esm/chunks/chunk-BA4LQJJQ.js +0 -1
  52. package/dist/esm/chunks/chunk-C5JYQCWH.js +0 -1
  53. package/dist/esm/chunks/extras-6POFBNOP.js +0 -1
  54. package/dist/esm/chunks/search-UJ73YBQ5.js +0 -1
  55. package/src/account/addresses-view.ts +0 -58
  56. package/src/account/answers.ts +0 -79
  57. package/src/account/markup.ts +0 -36
  58. package/src/account/operations.ts +0 -145
  59. package/src/account/order-lines.ts +0 -75
  60. package/src/account/order-list.ts +0 -107
  61. package/src/account/order-page.ts +0 -137
  62. package/src/account/page-answers.ts +0 -317
  63. package/src/account/page-events.ts +0 -253
  64. package/src/account/server-client.ts +0 -183
  65. package/src/account/subscriptions-view.ts +0 -115
  66. package/src/account-api.ts +0 -98
  67. package/src/account-marks.ts +0 -35
  68. package/src/account-pages.ts +0 -81
  69. package/src/account.ts +0 -284
  70. package/src/amounts.ts +0 -64
  71. package/src/analytics-shopify.ts +0 -246
  72. package/src/analytics.ts +0 -315
  73. package/src/api-version.ts +0 -79
  74. package/src/astro.ts +0 -272
  75. package/src/cart/cart-shape.ts +0 -25
  76. package/src/cart/checkout.ts +0 -101
  77. package/src/cart/drawer.ts +0 -125
  78. package/src/cart/mutations.ts +0 -237
  79. package/src/cart/render.ts +0 -266
  80. package/src/cart/store.ts +0 -279
  81. package/src/cart.ts +0 -345
  82. package/src/client.ts +0 -391
  83. package/src/collection.ts +0 -175
  84. package/src/config-sections.ts +0 -284
  85. package/src/config.ts +0 -480
  86. package/src/controls/cart-controls.ts +0 -123
  87. package/src/controls/discount.ts +0 -75
  88. package/src/controls/extras.ts +0 -54
  89. package/src/controls/navigation.ts +0 -77
  90. package/src/diagnose-markup.ts +0 -298
  91. package/src/diagnose.ts +0 -294
  92. package/src/dom.ts +0 -268
  93. package/src/extras.ts +0 -136
  94. package/src/fragments.ts +0 -261
  95. package/src/globals.d.ts +0 -15
  96. package/src/images.ts +0 -91
  97. package/src/index.ts +0 -415
  98. package/src/initial.ts +0 -101
  99. package/src/lazy-iife.ts +0 -197
  100. package/src/lazy.ts +0 -42
  101. package/src/loader.ts +0 -363
  102. package/src/market-codes.ts +0 -6
  103. package/src/markets-ui.ts +0 -227
  104. package/src/markets.ts +0 -246
  105. package/src/markup.ts +0 -127
  106. package/src/mounting.ts +0 -264
  107. package/src/page-market.ts +0 -110
  108. package/src/part-integrity.ts +0 -7
  109. package/src/parts/account-pages.ts +0 -7
  110. package/src/parts/account.ts +0 -7
  111. package/src/parts/analytics.ts +0 -7
  112. package/src/parts/diagnose.ts +0 -7
  113. package/src/parts/extras.ts +0 -7
  114. package/src/parts/markets.ts +0 -7
  115. package/src/parts/search.ts +0 -7
  116. package/src/presets/barba.ts +0 -194
  117. package/src/product-events.ts +0 -115
  118. package/src/product-render.ts +0 -218
  119. package/src/product-shape.ts +0 -49
  120. package/src/product-state.ts +0 -318
  121. package/src/product.ts +0 -308
  122. package/src/repeaters.ts +0 -161
  123. package/src/search.ts +0 -305
  124. package/src/selling-plans.ts +0 -145
  125. package/src/server.ts +0 -211
  126. package/src/shopify-values.ts +0 -91
  127. package/src/status.ts +0 -106
  128. package/src/storage.ts +0 -34
  129. package/src/store-html.ts +0 -359
  130. package/src/storefront/catalog.ts +0 -196
  131. package/src/storefront/json-ld.ts +0 -144
  132. package/src/variant-render.ts +0 -139
@@ -1,183 +0,0 @@
1
- /**
2
- * The browser's side of the Worker's account routes (`account.server`). The Worker holds the Shopify tokens, and
3
- * this browser only a session cookie its scripts can't read; what it keeps itself is the "may be logged in" hint,
4
- * which holds no secret. Storage throws in private mode and where the visitor blocks site data: the hint is then
5
- * not kept, and only pages with account markup load the part.
6
- */
7
- import { cfg } from '../config.ts';
8
- import { TetherError } from '../client.ts';
9
- import { Cart } from '../cart.ts';
10
- import { emit } from '../dom.ts';
11
- import { isRecord, textOrNull } from '../../server/src/shared/json.ts';
12
- import { messageOf } from '../../server/src/shared/error-message.ts';
13
- import { hintKey } from '../account-marks.ts';
14
- import { removeStored, setStored } from '../storage.ts';
15
- import { toAccountCustomer, toUserErrors } from './answers.ts';
16
- import type { AccountCustomer } from './answers.ts';
17
-
18
- /** The Worker's answer, or a 401: the session cookie is missing, has expired, or Shopify ended the login. */
19
- export type ServerAnswer = { kind: 'answer'; data: Record<string, unknown> } | { kind: 'logged-out' };
20
- type ServerLogin = { loggedIn: true; customer: AccountCustomer } | { loggedIn: false };
21
- export interface ServerRequest {
22
- method?: 'GET' | 'POST';
23
- body?: Record<string, unknown>;
24
- }
25
-
26
- /** The Worker's `/me` answer, until a change of the customer's data. */
27
- let known: ServerLogin | null = null;
28
-
29
- /**
30
- * @returns The Worker's account routes, without a trailing slash. `account.server` is a full URL or a path on this
31
- * site.
32
- * @throws {TetherError} `NOT_CONFIGURED` without `account.server`.
33
- */
34
- function serverBase(): string {
35
- const server = cfg.account?.server;
36
- if (!server) {
37
- throw new TetherError('Customer accounts need the Worker: set account.server', { code: 'NOT_CONFIGURED' });
38
- }
39
- return new URL(server, window.location.href).href.replace(/\/$/, '');
40
- }
41
-
42
- /**
43
- * Keeps the hint that makes the core load the part on the next page; without storage it is not kept (see the file's
44
- * comment).
45
- */
46
- function setLoginHint(loggedIn: boolean): void {
47
- if (loggedIn) setStored(hintKey(), '1');
48
- else removeStored(hintKey());
49
- }
50
-
51
- /** @throws {TetherError} `NETWORK` when the request fails before an answer. */
52
- async function fetchFromWorker(url: string, init: RequestInit): Promise<Response> {
53
- try {
54
- return await fetch(url, init);
55
- } catch (error) {
56
- throw new TetherError(`Network error: ${messageOf(error)}`, {
57
- code: 'NETWORK',
58
- });
59
- }
60
- }
61
-
62
- /** An error page that isn't JSON reads as an empty answer: the response's status then says what went wrong. */
63
- async function readJsonObjectOrEmpty(response: Response): Promise<Record<string, unknown>> {
64
- let json: unknown;
65
- try {
66
- json = await response.json();
67
- } catch {
68
- return {};
69
- }
70
- return isRecord(json) ? json : {};
71
- }
72
-
73
- /**
74
- * One request to the Worker, with the session cookie. A POST carries the header the Worker requires against
75
- * cross-site forms.
76
- *
77
- * @throws {TetherError} `NOT_CONFIGURED` without `account.server`, `INVALID` for refused input, `HTTP_<status>` for
78
- * any other failure but a 401, with the Worker's `userErrors`; `NETWORK` when the Worker can't be reached.
79
- */
80
- export async function serverFetch(path: string, { method = 'GET', body }: ServerRequest = {}): Promise<ServerAnswer> {
81
- const init: RequestInit = { method, credentials: 'include' };
82
- if (method === 'POST') init.headers = { 'Content-Type': 'application/json', 'X-Tether-Account': '1' };
83
- if (body) init.body = JSON.stringify(body);
84
- const response = await fetchFromWorker(`${serverBase()}${path}`, init);
85
- if (response.status === 401) return { kind: 'logged-out' };
86
- const data = await readJsonObjectOrEmpty(response);
87
- if (!response.ok) {
88
- const reason = textOrNull(data['error']) ?? String(response.status);
89
- const userErrors = toUserErrors(data['userErrors']);
90
- throw new TetherError(`Customer accounts: ${reason}`, {
91
- status: response.status,
92
- ...(userErrors.length > 0 && { userErrors }),
93
- // The Worker marks refused input (a 400, or a 404 for a contract that isn't the customer's) with `code`.
94
- ...(data['code'] === 'INVALID' && { code: 'INVALID' }),
95
- });
96
- }
97
- return { kind: 'answer', data };
98
- }
99
-
100
- /**
101
- * Who is logged in, asked once and then kept; the "may be logged in" hint follows the answer.
102
- *
103
- * @throws {TetherError} When the Worker can't be reached or fails: that says nothing about the login.
104
- */
105
- export async function serverLogin(): Promise<ServerLogin> {
106
- if (!known) {
107
- const answer = await serverFetch('/me');
108
- known =
109
- answer.kind === 'answer' && answer.data['loggedIn'] === true
110
- ? { loggedIn: true, customer: toAccountCustomer(answer.data['customer']) }
111
- : { loggedIn: false };
112
- }
113
- setLoginHint(known.loggedIn);
114
- return known;
115
- }
116
-
117
- /** @returns True when the Worker last said a customer is logged in. */
118
- export const isServerLoggedIn = (): boolean => known?.loggedIn === true;
119
-
120
- /** Asks the Worker again on the next `serverLogin()`, after a change of the customer's data. */
121
- export function forgetServerLogin(): void {
122
- known = null;
123
- }
124
-
125
- /** Goes to the Worker's (or Shopify's) pages, through `account.navigate` when the site replaces the redirect. */
126
- function navigate(url: string): void {
127
- const replacement = cfg.account?.navigate;
128
- if (replacement) replacement(url);
129
- else window.location.assign(url);
130
- }
131
-
132
- /**
133
- * @param locale The caller's choice.
134
- * @returns The language of Shopify's login page: the caller's, `account.locale`, else the site's; `''` for Shopify's
135
- * default.
136
- */
137
- const loginLanguage = (locale: string | undefined): string =>
138
- locale || cfg.account?.locale || (cfg.locale || '').split('-')[0] || '';
139
-
140
- /**
141
- * To the Worker's login, which comes back to `returnTo` with `?account=<outcome>`. The cart is linked later, at
142
- * checkout, through the Worker's protected `POST /cart`.
143
- *
144
- * @throws {TetherError} `NOT_CONFIGURED` without `account.server`.
145
- */
146
- export function serverLoginRedirect({ returnTo, locale }: { returnTo: string; locale?: string | undefined }): void {
147
- const url = new URL(`${serverBase()}/login`);
148
- url.searchParams.set('returnTo', returnTo);
149
- const language = loginLanguage(locale);
150
- if (language) url.searchParams.set('locale', language);
151
- if (cfg.country) url.searchParams.set('country', cfg.country.toUpperCase());
152
- navigate(url.toString());
153
- }
154
-
155
- /**
156
- * The logged-in customer's checkout, for `Cart.setCheckoutResolver`: the Worker links the cart to the customer and
157
- * answers with its checkout URL.
158
- *
159
- * @returns `null` when nobody is logged in or the Worker linked no cart, so the cart's own checkout URL is used.
160
- * @throws {TetherError} When the Worker fails; the cart reports it and checks out without the login.
161
- */
162
- export async function serverCheckoutUrl(): Promise<string | null> {
163
- const cartId = Cart.id();
164
- if (!(await serverLogin()).loggedIn || !cartId) return null;
165
- const answer = await serverFetch('/cart', { method: 'POST', body: { cartId } });
166
- if (answer.kind === 'logged-out') return null;
167
- return textOrNull(answer.data['checkoutUrl']);
168
- }
169
-
170
- /**
171
- * Ends the session at the Worker, which also unlinks the cart, then goes on to Shopify's logout when the Worker says
172
- * where. Sends `tether:account-logout`.
173
- */
174
- export async function serverLogout(returnTo: string): Promise<'redirected' | 'stayed'> {
175
- const answer = await serverFetch('/logout', { method: 'POST', body: { returnTo, cartId: Cart.id() } });
176
- known = null;
177
- setLoginHint(false);
178
- emit('account-logout', {});
179
- const logoutUrl = answer.kind === 'answer' ? textOrNull(answer.data['logoutUrl']) : null;
180
- if (!logoutUrl) return 'stayed';
181
- navigate(logoutUrl);
182
- return 'redirected';
183
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * The customer's subscriptions (`tether-subscriptions`), with `tether-show="subscriptions-loading"`,
3
- * `subscriptions-empty` and `subscriptions-error`. Each row's `tether-subscription-show` conditions and action buttons
4
- * follow the contract's status and its next billing cycle.
5
- */
6
- import { reportError } from '../config.ts';
7
- import { attr, formatDate, formatMoney, get, qsa, repeat, sel, setImage, setText } from '../dom.ts';
8
- import { bindsIn, enumText, ownValue, showIn } from './markup.ts';
9
- import { subscriptions } from './operations.ts';
10
- import type { SubscriptionContract, SubscriptionLine } from './page-answers.ts';
11
-
12
- /** @returns The row's `tether-subscription-show` conditions, `can-<action>` among them. */
13
- function conditionsOf(contract: SubscriptionContract): Record<string, boolean> {
14
- const next = contract.upcomingBillingCycles.nodes[0];
15
- const status = contract.status;
16
- const active = status === 'ACTIVE';
17
- return {
18
- active,
19
- paused: status === 'PAUSED',
20
- cancelled: status === 'CANCELLED',
21
- expired: status === 'EXPIRED',
22
- failed: status === 'FAILED',
23
- skipped: Boolean(next?.skipped),
24
- 'can-pause': active,
25
- 'can-resume': status === 'PAUSED' || status === 'FAILED',
26
- 'can-skip': active && next !== undefined && !next.skipped,
27
- 'can-unskip': active && Boolean(next?.skipped),
28
- 'can-cancel': active || status === 'PAUSED' || status === 'FAILED',
29
- };
30
- }
31
-
32
- /** @returns `month`, `3 months`; `''` without a delivery policy. */
33
- function intervalText(contract: SubscriptionContract): string {
34
- const unit = enumText(contract.deliveryPolicy?.interval);
35
- if (!unit) return '';
36
- const count = contract.deliveryPolicy?.intervalCount?.count ?? 1;
37
- return count <= 1 ? unit : `${String(count)} ${unit}s`;
38
- }
39
-
40
- /** @returns The text of each `tether-subscription-bind` value. */
41
- function contractTexts(contract: SubscriptionContract): Record<string, string> {
42
- const lines = contract.lines.nodes;
43
- const total = lines.reduce((sum, line) => sum + Number.parseFloat(line.lineDiscountedPrice?.amount ?? '0'), 0);
44
- return {
45
- status: enumText(contract.status),
46
- next: formatDate(contract.nextBillingDate),
47
- interval: intervalText(contract),
48
- products: lines.map((line) => `${String(line.quantity)}× ${line.title ?? ''}`).join(', '),
49
- total: formatMoney(
50
- lines.length && contract.currencyCode ? { amount: String(total), currencyCode: contract.currencyCode } : null,
51
- ),
52
- delivery: formatMoney(contract.deliveryPrice),
53
- };
54
- }
55
-
56
- function fillLine(row: HTMLElement, line: SubscriptionLine): void {
57
- const texts: Record<string, string> = {
58
- title: line.title ?? '',
59
- 'variant-title': line.variantTitle || '',
60
- quantity: String(line.quantity),
61
- price: formatMoney(line.currentPrice),
62
- };
63
- bindsIn(row, 'subscription-line').forEach((el) => {
64
- const key = get(el, 'subscription-line') ?? '';
65
- if (key === 'image') {
66
- if (line.image) setImage(el, line.image.url, line.image.altText || line.title || '');
67
- return;
68
- }
69
- const text = ownValue(texts, key);
70
- if (text !== undefined) setText(el, text);
71
- });
72
- }
73
-
74
- function fillContract(row: HTMLElement, contract: SubscriptionContract): void {
75
- row.dataset['tetherSubscription'] = contract.id;
76
- row.setAttribute(attr('subscription-status'), enumText(contract.status));
77
- const texts = contractTexts(contract);
78
- qsa(row, sel('subscription-bind')).forEach((el) => {
79
- const text = ownValue(texts, get(el, 'subscription-bind') ?? '');
80
- if (text !== undefined) setText(el, text);
81
- });
82
- qsa(row, sel('subscription-lines')).forEach((box) => {
83
- repeat(box, contract.lines.nodes, fillLine);
84
- });
85
- const conditions = conditionsOf(contract);
86
- showIn(row, 'subscription-show', conditions);
87
- qsa(row, sel('subscription-action')).forEach((button) => {
88
- const allowed = ownValue(conditions, `can-${get(button, 'subscription-action') ?? ''}`) === true;
89
- if ('disabled' in button) button.disabled = !allowed;
90
- button.classList.toggle('is-disabled', !allowed);
91
- });
92
- }
93
-
94
- /** Loads and renders the subscriptions. A failure is reported and shows `subscriptions-error`. */
95
- export async function renderSubscriptions(root: ParentNode): Promise<void> {
96
- const boxes = qsa(root, sel('subscriptions'));
97
- if (!boxes.length) return;
98
- showIn(root, 'show', { 'subscriptions-loading': true, 'subscriptions-empty': false });
99
- let list: SubscriptionContract[];
100
- try {
101
- list = await subscriptions();
102
- } catch (error) {
103
- reportError(error, 'subscriptions');
104
- showIn(root, 'show', { 'subscriptions-loading': false, 'subscriptions-error': true });
105
- return;
106
- }
107
- showIn(root, 'show', {
108
- 'subscriptions-loading': false,
109
- 'subscriptions-empty': list.length === 0,
110
- 'subscriptions-error': false,
111
- });
112
- boxes.forEach((box) => {
113
- repeat(box, list, fillContract);
114
- });
115
- }
@@ -1,98 +0,0 @@
1
- /**
2
- * The core's side of customer accounts, which are an optional part: whether a page needs the part, and
3
- * `Tether.account`, whose functions load it on first call. Every function returns a promise, the part's own sync ones
4
- * (`isLoggedIn`) too, because the part may still have to load.
5
- */
6
- import { cfg, reportError } from './config.ts';
7
- import { attr } from './dom.ts';
8
- import { loadPart } from './lazy.ts';
9
- import { within } from './mounting.ts';
10
- import { hintKey, isLoginOutcome } from './account-marks.ts';
11
- import { getStored } from './storage.ts';
12
- import type { Parts } from './lazy.ts';
13
-
14
- type AccountPart = Parts['account'];
15
- type AccountResult<Name extends keyof AccountPart> = Awaited<ReturnType<AccountPart[Name]>>;
16
- type AccountFunction<Name extends keyof AccountPart> = (
17
- ...args: Parameters<AccountPart[Name]>
18
- ) => Promise<AccountResult<Name>>;
19
- type AccountApi = { [Name in keyof AccountPart]: AccountFunction<Name> };
20
-
21
- /** The attributes of the account markup: a page with one of them loads the part. */
22
- const ACCOUNT_ATTRIBUTES = [
23
- 'account-login',
24
- 'account-bind',
25
- 'account-link',
26
- 'orders',
27
- 'order',
28
- 'addresses',
29
- 'subscriptions',
30
- 'profile-form',
31
- 'address-form',
32
- ];
33
-
34
- /** @returns A selector for every element the account part fills in or shows. */
35
- const accountSelector = (): string =>
36
- [...ACCOUNT_ATTRIBUTES.map((name) => `[${attr(name)}]`), `[${attr('show')}^="logged-"]`].join(',');
37
-
38
- /**
39
- * Whether this browser keeps the "may be logged in" hint, so checkout on a page without account markup still knows
40
- * the customer.
41
- *
42
- * @returns False where the browser blocks storage, which then holds no hint.
43
- */
44
- function hasLoginHint(): boolean {
45
- return Boolean(getStored(hintKey()));
46
- }
47
-
48
- /**
49
- * Loads the account part and mounts it on `root`, when accounts are configured and the page needs them: account
50
- * markup in `root`, a login coming back from the Worker (`?account=`), or the "may be logged in" hint.
51
- */
52
- export function mountAccountIfUsed(root: ParentNode): void {
53
- if (!cfg.account) return;
54
- const needed =
55
- within(root, accountSelector()).length > 0 ||
56
- isLoginOutcome(new URLSearchParams(window.location.search).get('account')) ||
57
- hasLoginHint();
58
- if (!needed) return;
59
- loadPart('account')
60
- .then((part) => part.mountAccount(root))
61
- .catch((error: unknown) => {
62
- reportError(error, 'account');
63
- });
64
- }
65
-
66
- /** @returns `name` of the account part, called once the part has loaded. */
67
- function fromPart<Name extends keyof AccountPart>(name: Name): AccountFunction<Name> {
68
- return (...args) =>
69
- loadPart('account').then((part) => {
70
- // `Name` picks one function of the part, and `args` are that function's parameters.
71
- const call = part[name] as (
72
- ...callArgs: Parameters<AccountPart[Name]>
73
- ) => AccountResult<Name> | PromiseLike<AccountResult<Name>>;
74
- return call(...args);
75
- });
76
- }
77
-
78
- /**
79
- * `Tether.account`: the account part's functions, each loading the part on first call. A plain object, so `await
80
- * Tether.account` and `Object.keys(Tether.account)` behave as for any object.
81
- */
82
- export const accountApi: AccountApi = {
83
- login: fromPart('login'),
84
- logout: fromPart('logout'),
85
- isLoggedIn: fromPart('isLoggedIn'),
86
- customer: fromPart('customer'),
87
- orders: fromPart('orders'),
88
- order: fromPart('order'),
89
- updateProfile: fromPart('updateProfile'),
90
- addresses: fromPart('addresses'),
91
- saveAddress: fromPart('saveAddress'),
92
- deleteAddress: fromPart('deleteAddress'),
93
- subscriptions: fromPart('subscriptions'),
94
- subscriptionAction: fromPart('subscriptionAction'),
95
- requestReturn: fromPart('requestReturn'),
96
- render: fromPart('render'),
97
- mountAccount: fromPart('mountAccount'),
98
- };
@@ -1,35 +0,0 @@
1
- /**
2
- * What tells a page that customer accounts are in use in this browser: the "may be logged in" hint the account part
3
- * keeps in `localStorage`, and the Worker's `?account=` mark after a login. The core reads them to decide whether a
4
- * page loads the part, and the part writes the hint, so both take them from here.
5
- */
6
- import { cfg } from './config.ts';
7
- import { removeStored } from './storage.ts';
8
-
9
- /**
10
- * What the Worker's login redirect says in `?account=`: `in` after a login, `expired` when the login took too long,
11
- * `error` when it failed.
12
- */
13
- type LoginOutcome = 'in' | 'expired' | 'error';
14
-
15
- /** The "may be logged in" hint's key: it makes the core load the part on the next page, and holds no secret. */
16
- export const hintKey = (): string => `${cfg.prefix}:account-hint:${cfg.domain}`;
17
-
18
- /** Removes a key from both storage areas, each on its own: a blocked one doesn't keep the key in the other. */
19
- function removeFromBothAreas(key: string): void {
20
- removeStored(key, 'sessionStorage');
21
- removeStored(key, 'localStorage');
22
- }
23
-
24
- /**
25
- * Removes the customer tokens and pending login that Tether 0.6's browser-mode accounts kept in this browser. The
26
- * session held a refresh token with the customer's full scope, so it must not stay behind once accounts run through
27
- * the Worker. TODO: remove in 0.8.0, when no visitor's browser still holds a 0.6 session.
28
- */
29
- export function forgetBrowserModeTokens(): void {
30
- removeFromBothAreas(`${cfg.prefix}:account:${cfg.domain}`);
31
- removeFromBothAreas(`${cfg.prefix}:account-login:${cfg.domain}`);
32
- }
33
-
34
- export const isLoginOutcome = (value: string | null): value is LoginOutcome =>
35
- value === 'in' || value === 'expired' || value === 'error';
@@ -1,81 +0,0 @@
1
- /**
2
- * Customer account pages, an optional part the account part loads on pages that use them: the order page with
3
- * returns, the profile form, addresses and subscriptions. Each operation is one of the Worker's fixed routes, which
4
- * checks the input (account/operations.ts).
5
- */
6
- import { reportError } from './config.ts';
7
- import { qsa, sel } from './dom.ts';
8
- import { pagesContext } from './account/operations.ts';
9
- import { renderOrder, showOrderState } from './account/order-page.ts';
10
- import { renderAddresses } from './account/addresses-view.ts';
11
- import { renderSubscriptions } from './account/subscriptions-view.ts';
12
- import { listenToPages } from './account/page-events.ts';
13
- import { showIn } from './account/markup.ts';
14
- import type { AccountCustomer } from './account/answers.ts';
15
-
16
- export {
17
- setup,
18
- order,
19
- updateProfile,
20
- addresses,
21
- saveAddress,
22
- deleteAddress,
23
- subscriptions,
24
- subscriptionAction,
25
- requestReturn,
26
- } from './account/operations.ts';
27
-
28
- /** The profile fields a `tether-profile-form` is filled with. */
29
- const PROFILE_FIELDS = ['firstName', 'lastName'] as const;
30
-
31
- /** Fills the profile form with the customer's name, leaving a field the visitor has typed in alone. */
32
- async function renderProfile(form: HTMLElement): Promise<void> {
33
- if (!(form instanceof window.HTMLFormElement)) return;
34
- let customer: AccountCustomer | null;
35
- try {
36
- customer = await pagesContext().customer();
37
- } catch (error) {
38
- // The form stays empty and still saves: only the prefill is missing.
39
- reportError(error, 'account');
40
- return;
41
- }
42
- if (!customer) return;
43
- const fields = form.elements;
44
- PROFILE_FIELDS.forEach((name) => {
45
- const input = fields.namedItem(name);
46
- const isTextField = input instanceof window.HTMLInputElement || input instanceof window.HTMLTextAreaElement;
47
- if (isTextField && !input.dataset['tetherTouched']) input.value = customer[name] ?? '';
48
- });
49
- }
50
-
51
- let listening = false;
52
-
53
- /** Renders the order page, profile form, addresses and subscriptions in `root`: only what it has. */
54
- export async function renderPages(root: ParentNode = document): Promise<void> {
55
- if (!listening) {
56
- listening = true;
57
- listenToPages();
58
- }
59
- await Promise.all([
60
- ...qsa(root, sel('order')).map((el) => renderOrder(el)),
61
- ...qsa(root, sel('profile-form')).map((form) => renderProfile(form)),
62
- renderAddresses(root),
63
- renderSubscriptions(root),
64
- ]);
65
- }
66
-
67
- /**
68
- * The error state of every account page in `root`, for when nobody can say whether a customer is logged in (the
69
- * Worker or Shopify can't be reached).
70
- */
71
- export function showUnavailable(root: ParentNode): void {
72
- qsa(root, sel('order')).forEach((el) => {
73
- showOrderState(el, 'error');
74
- });
75
- showIn(root, 'show', {
76
- 'addresses-loading': false,
77
- 'addresses-error': true,
78
- 'subscriptions-loading': false,
79
- 'subscriptions-error': true,
80
- });
81
- }