@foxtware/mineral 0.1.27 → 0.1.29

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 (178) hide show
  1. package/.creds.yml.sample +29 -0
  2. package/AGENTS.md +24 -0
  3. package/_build_scripts/createNewFunction.js +26 -3
  4. package/api/dropbox/docs.md +7 -0
  5. package/api/dropbox/dropbox.constants.js +10 -0
  6. package/api/dropbox/dropbox.utils.js +67 -0
  7. package/api/dropbox/dropboxAccountGet.js +64 -0
  8. package/api/dropbox/dropboxFileCopy.js +67 -0
  9. package/api/dropbox/dropboxFileDelete.js +89 -0
  10. package/api/dropbox/dropboxFileDownload.js +139 -0
  11. package/api/dropbox/dropboxFileMetadataGet.js +100 -0
  12. package/api/dropbox/dropboxFileMove.js +67 -0
  13. package/api/dropbox/dropboxFileUpload.js +129 -0
  14. package/api/dropbox/dropboxFolderCreate.js +68 -0
  15. package/api/dropbox/dropboxFolderList.js +66 -0
  16. package/api/dropbox/dropboxGet.js +158 -0
  17. package/api/dropbox/dropboxSearch.js +161 -0
  18. package/api/dropbox/dropboxSharedLinkCreate.js +68 -0
  19. package/api/dropbox/dropboxSpaceUsageGet.js +55 -0
  20. package/api/dropbox/dropboxTemporaryLinkGet.js +75 -0
  21. package/api/fastsimon/.gitkeep +0 -0
  22. package/api/fastsimon/docs.md +14 -0
  23. package/api/fastsimon/fastsimon.constants.js +18 -0
  24. package/api/fastsimon/fastsimon.utils.js +246 -0
  25. package/api/fastsimon/fastsimonSearch.js +84 -0
  26. package/api/figma/docs.md +3 -3
  27. package/api/figma/figma.constants.js +1 -1
  28. package/api/figma/figma.utils.js +13 -2
  29. package/api/figma/figmaActivityLogsGet.js +44 -0
  30. package/api/figma/figmaAiUsageDailyGet.js +44 -0
  31. package/api/figma/figmaComponentGet.js +48 -0
  32. package/api/figma/figmaComponentSetGet.js +48 -0
  33. package/api/figma/figmaDevResourcesCreate.js +47 -0
  34. package/api/figma/figmaDevResourcesUpdate.js +47 -0
  35. package/api/figma/figmaDeveloperLogsCreate.js +47 -0
  36. package/api/figma/figmaDiscoveryGet.js +44 -0
  37. package/api/figma/figmaFileCommentCreate.js +50 -0
  38. package/api/figma/figmaFileCommentDelete.js +51 -0
  39. package/api/figma/figmaFileCommentReactionCreate.js +53 -0
  40. package/api/figma/figmaFileCommentReactionDelete.js +51 -0
  41. package/api/figma/figmaFileCommentReactionsGet.js +51 -0
  42. package/api/figma/figmaFileCommentsGet.js +48 -0
  43. package/api/figma/figmaFileComponentSetsGet.js +48 -0
  44. package/api/figma/figmaFileComponentsGet.js +48 -0
  45. package/api/figma/figmaFileDevResourceDelete.js +51 -0
  46. package/api/figma/figmaFileDevResourcesGet.js +48 -0
  47. package/api/figma/figmaFileGet.js +48 -0
  48. package/api/figma/figmaFileImageFillsGet.js +48 -0
  49. package/api/figma/figmaFileImagesGet.js +48 -0
  50. package/api/figma/figmaFileMetaGet.js +48 -0
  51. package/api/figma/figmaFileNodesGet.js +48 -0
  52. package/api/figma/figmaFileStylesGet.js +48 -0
  53. package/api/figma/figmaFileVersionsGet.js +48 -0
  54. package/api/figma/figmaFolderFilesGet.js +48 -0
  55. package/api/figma/figmaFolderFoldersGet.js +48 -0
  56. package/api/figma/figmaFolderMetaGet.js +48 -0
  57. package/api/figma/figmaGet.js +15 -63
  58. package/api/figma/figmaMeGet.js +53 -0
  59. package/api/figma/figmaOembedGet.js +44 -0
  60. package/api/figma/figmaPaymentsGet.js +44 -0
  61. package/api/figma/figmaProjectFilesGet.js +48 -0
  62. package/api/figma/figmaProjectMetaGet.js +48 -0
  63. package/api/figma/figmaStyleGet.js +48 -0
  64. package/api/figma/figmaTeamComponentSetsGet.js +48 -0
  65. package/api/figma/figmaTeamComponentsGet.js +48 -0
  66. package/api/figma/figmaTeamFoldersGet.js +48 -0
  67. package/api/figma/figmaTeamProjectsGet.js +48 -0
  68. package/api/figma/figmaTeamStylesGet.js +48 -0
  69. package/api/figma/figmaTeamWebhooksGet.js +47 -0
  70. package/api/figma/figmaVariablesLocalGet.js +48 -0
  71. package/api/figma/figmaVariablesPublishedGet.js +48 -0
  72. package/api/figma/figmaVariablesUpdate.js +50 -0
  73. package/api/figma/figmaWebhookCreate.js +47 -0
  74. package/api/figma/figmaWebhookDelete.js +48 -0
  75. package/api/figma/figmaWebhookGet.js +46 -0
  76. package/api/figma/figmaWebhookRequestsGet.js +47 -0
  77. package/api/figma/figmaWebhookUpdate.js +50 -0
  78. package/api/figma/figmaWebhooksGet.js +47 -0
  79. package/api/google/docs.md +1 -0
  80. package/api/google/google.constants.js +1 -0
  81. package/api/google/google.utils.js +21 -0
  82. package/api/google/googleanalyticsMetadataGet.js +62 -0
  83. package/api/google/googleanalyticsRealtimeReportRun.js +103 -0
  84. package/api/google/googleanalyticsReportRun.js +114 -0
  85. package/api/gorgias/gorgiasTicketCreate.js +1 -1
  86. package/api/gorgias/gorgiasTicketMessageCreate.js +1 -1
  87. package/api/gorgias/gorgiasTicketUpdate.js +1 -1
  88. package/api/linear/linearAttachmentCreate.js +1 -1
  89. package/api/linear/linearCommentCreate.js +1 -1
  90. package/api/linear/linearCommentUpdate.js +1 -1
  91. package/api/linear/linearIssueLabelCreate.js +1 -1
  92. package/api/linear/linearIssueUpdate.js +1 -1
  93. package/api/linear/linearProjectCreate.js +1 -1
  94. package/api/linear/linearProjectUpdate.js +1 -1
  95. package/api/linear/linearWebhookCreate.js +1 -1
  96. package/api/salesforce/salesforce.constants.js +13 -0
  97. package/api/salesforce/salesforce.utils.js +61 -0
  98. package/api/salesforce/salesforceAuthGet.js +115 -0
  99. package/api/salesforce/salesforceComposite.js +79 -0
  100. package/api/salesforce/salesforceCompositeBatch.js +73 -0
  101. package/api/salesforce/salesforceLimitsGet.js +55 -0
  102. package/api/salesforce/salesforceQuery.js +69 -0
  103. package/api/salesforce/salesforceQueryAll.js +62 -0
  104. package/api/salesforce/salesforceQueryMore.js +75 -0
  105. package/api/salesforce/salesforceRecentItemsGet.js +63 -0
  106. package/api/salesforce/salesforceResourcesGet.js +55 -0
  107. package/api/salesforce/salesforceSearch.js +62 -0
  108. package/api/salesforce/salesforceSobjectBasicInfoGet.js +81 -0
  109. package/api/salesforce/salesforceSobjectBlobGet.js +67 -0
  110. package/api/salesforce/salesforceSobjectCollectionCreate.js +78 -0
  111. package/api/salesforce/salesforceSobjectCollectionDelete.js +70 -0
  112. package/api/salesforce/salesforceSobjectCollectionGet.js +75 -0
  113. package/api/salesforce/salesforceSobjectCollectionUpdate.js +74 -0
  114. package/api/salesforce/salesforceSobjectCreate.js +66 -0
  115. package/api/salesforce/salesforceSobjectDelete.js +86 -0
  116. package/api/salesforce/salesforceSobjectDeleteByExternalId.js +91 -0
  117. package/api/salesforce/salesforceSobjectDeletedGet.js +71 -0
  118. package/api/salesforce/salesforceSobjectDescribe.js +81 -0
  119. package/api/salesforce/salesforceSobjectDescribeLayouts.js +64 -0
  120. package/api/salesforce/salesforceSobjectGet.js +93 -0
  121. package/api/salesforce/salesforceSobjectGetByExternalId.js +98 -0
  122. package/api/salesforce/salesforceSobjectTreeCreate.js +79 -0
  123. package/api/salesforce/salesforceSobjectUpdate.js +94 -0
  124. package/api/salesforce/salesforceSobjectUpdatedGet.js +71 -0
  125. package/api/salesforce/salesforceSobjectUpsert.js +74 -0
  126. package/api/salesforce/salesforceSobjectsDescribeGlobal.js +55 -0
  127. package/api/salesforce/salesforceVersionsGet.js +62 -0
  128. package/api/shopify/shopify.utils.js +53 -4
  129. package/api/shopify/shopifyMetaobjectCreate.js +79 -0
  130. package/api/shopify/shopifyMetaobjectDelete.js +90 -0
  131. package/api/shopify/shopifyMetaobjectGet.js +80 -0
  132. package/api/shopify/shopifyMetaobjectUpdate.js +108 -0
  133. package/api/shopify/shopifyStorefrontSearch.js +158 -0
  134. package/api/spotify/docs.md +8 -0
  135. package/api/spotify/spotify.constants.js +12 -0
  136. package/api/spotify/spotify.utils.js +106 -0
  137. package/api/spotify/spotifyAlbumGet.js +76 -0
  138. package/api/spotify/spotifyAlbumTracksGet.js +49 -0
  139. package/api/spotify/spotifyArtistAlbumsGet.js +55 -0
  140. package/api/spotify/spotifyArtistGet.js +71 -0
  141. package/api/spotify/spotifyArtistTopTracksGet.js +56 -0
  142. package/api/spotify/spotifyGet.js +171 -0
  143. package/api/spotify/spotifyMeGet.js +48 -0
  144. package/api/spotify/spotifyPlayerCurrentlyPlayingGet.js +62 -0
  145. package/api/spotify/spotifyPlayerDevicesGet.js +51 -0
  146. package/api/spotify/spotifyPlayerGet.js +63 -0
  147. package/api/spotify/spotifyPlayerNext.js +55 -0
  148. package/api/spotify/spotifyPlayerPause.js +55 -0
  149. package/api/spotify/spotifyPlayerPlay.js +70 -0
  150. package/api/spotify/spotifyPlayerPrevious.js +55 -0
  151. package/api/spotify/spotifyPlaylistCreate.js +63 -0
  152. package/api/spotify/spotifyPlaylistGet.js +91 -0
  153. package/api/spotify/spotifyPlaylistItemsAdd.js +61 -0
  154. package/api/spotify/spotifyPlaylistItemsGet.js +58 -0
  155. package/api/spotify/spotifyPlaylistItemsRemove.js +67 -0
  156. package/api/spotify/spotifyPlaylistUpdate.js +64 -0
  157. package/api/spotify/spotifyPlaylistsGet.js +47 -0
  158. package/api/spotify/spotifySavedTracksGet.js +46 -0
  159. package/api/spotify/spotifySavedTracksRemove.js +59 -0
  160. package/api/spotify/spotifySavedTracksSave.js +59 -0
  161. package/api/spotify/spotifySearch.js +174 -0
  162. package/api/spotify/spotifyTrackGet.js +76 -0
  163. package/api/tableau/tableau.constants.js +8 -0
  164. package/api/tableau/tableau.utils.js +93 -0
  165. package/api/tableau/tableauGet.js +174 -0
  166. package/api/tableau/tableauUserAdd.js +16 -94
  167. package/api/tableau/tableauUsersGet.js +46 -134
  168. package/api/tagalys/docs.md +2 -2
  169. package/api/tagalys/tagalys.constants.js +17 -0
  170. package/api/tagalys/tagalys.utils.js +125 -0
  171. package/api/tagalys/tagalysAnalyticsEventSend.js +125 -0
  172. package/api/tagalys/tagalysCollectionGet.js +100 -0
  173. package/api/tagalys/tagalysPopularSearchesGet.js +60 -0
  174. package/api/tagalys/tagalysRecommendationGet.js +109 -0
  175. package/api/tagalys/tagalysSearch.js +15 -89
  176. package/api/tagalys/tagalysSearchSuggestionsGet.js +76 -0
  177. package/package.json +2 -1
  178. package/server.js +3 -1
@@ -1,155 +1,67 @@
1
+ // https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_users_and_groups.htm#query_users_on_site
1
2
  // GET /api/{api-version}/sites/{site-id}/users is paginated (default pageSize
2
3
  // is 100, max 1000), so this walks all pages and returns the full list.
3
4
 
4
- const { ArgsWarden, logDeep } = require('../utils');
5
- const { resolveCreds } = require('../pipelineSteps');
6
- const {
7
- FetchClient,
8
- appendUrlToBase,
9
- fetchClientCommonSteps,
10
- } = require('../utils');
5
+ const { ArgsWarden } = require('../utils');
6
+ const { credsValidator } = require('../validators');
7
+ const { tableauGet } = require('../tableau/tableauGet');
8
+ const { MAX_PER_PAGE } = require('../tableau/tableau.constants');
11
9
 
12
- const DEFAULT_API_VERSION = '3.22';
13
- const PAGE_SIZE = 1000; // Tableau's max page size
14
-
15
- const tokenCache = new Map();
16
-
17
- const tableauSignIn = async ({
18
- SERVER_URL,
19
- PAT_NAME,
20
- PAT_SECRET,
21
- SITE_CONTENT_URL = '',
22
- }) => {
23
- const cacheKey = `${ SERVER_URL }::${ SITE_CONTENT_URL }`;
24
- const cached = tokenCache.get(cacheKey);
25
- if (cached && cached.expiresAt > Date.now()) {
26
- return cached;
27
- }
28
-
29
- const response = await fetch(`${ SERVER_URL }/api/${ DEFAULT_API_VERSION }/auth/signin`, {
30
- method: 'POST',
31
- headers: {
32
- 'Content-Type': 'application/json',
33
- Accept: 'application/json',
34
- },
35
- body: JSON.stringify({
36
- credentials: {
37
- personalAccessTokenName: PAT_NAME,
38
- personalAccessTokenSecret: PAT_SECRET,
39
- site: { contentUrl: SITE_CONTENT_URL },
40
- },
41
- }),
42
- });
43
-
44
- if (!response.ok) {
45
- throw new Error(`Tableau sign-in failed: ${ response.status } ${ await response.text() }`);
46
- }
47
-
48
- const { credentials } = await response.json();
49
-
50
- const session = {
51
- token: credentials.token,
52
- siteId: credentials.site.id,
53
- expiresAt: Date.now() + 1000 * 60 * 60 * 2,
54
- };
55
-
56
- tokenCache.set(cacheKey, session);
57
- return session;
58
- };
59
-
60
- const useUrlAndAuthHeaders = async (state) => {
61
- const { requestPayload, context } = state;
62
- const { creds } = context;
63
-
64
- const { token, siteId } = await tableauSignIn(creds);
65
-
66
- return {
67
- requestPayload: {
68
- ...requestPayload,
69
- url: appendUrlToBase(
70
- `${ creds.SERVER_URL }/api/${ DEFAULT_API_VERSION }`,
71
- requestPayload.url.replace('{siteId}', siteId),
72
- ),
73
- headers: {
74
- 'X-Tableau-Auth': token,
75
- 'Content-Type': 'application/json',
76
- Accept: 'application/json',
77
- ...requestPayload.headers,
78
- },
79
- },
80
- };
81
- };
82
-
83
- const tableauClient = new FetchClient({
84
- pipeline: [
85
- resolveCreds,
86
- useUrlAndAuthHeaders,
87
- 'fetch',
88
- fetchClientCommonSteps.exitEarlyOnNotOk,
89
- ],
90
- });
91
-
92
- const argsWarden = new ArgsWarden([]);
10
+ const argsWarden = new ArgsWarden([
11
+ ['credsPayload', credsValidator],
12
+ ]);
93
13
 
94
14
  // Optional filter, e.g. { filter: "siteRole:eq:Explorer" } or
95
15
  // { filter: "name:has:jane" } per Tableau's filter-expression syntax.
96
- const tableauUsersGet = async ({ filter } = {}) => {
97
- const rejectResponse = await argsWarden.responseIfRejectingArgs({});
16
+ const tableauUsersGet = async (
17
+ credsPayload,
18
+ {
19
+ filter,
20
+ perPage = MAX_PER_PAGE,
21
+ fetchClient,
22
+ ...getterOptions
23
+ } = {},
24
+ ) => {
25
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
26
+ credsPayload,
27
+ });
98
28
  if (rejectResponse) {
99
29
  return rejectResponse;
100
30
  }
101
31
 
102
- const users = [];
103
- let pageNumber = 1;
104
-
105
- while (true) {
106
- const query = new URLSearchParams({
107
- pageSize: String(PAGE_SIZE),
108
- pageNumber: String(pageNumber),
32
+ return tableauGet(credsPayload, '/sites/{siteId}/users', {
33
+ params: {
109
34
  ...(filter ? { filter } : {}),
110
- });
111
-
112
- const response = await tableauClient.fetch({
113
- context: {
114
- credsPayload: { credsPath: ['tableau'] },
115
- },
116
- requestPayload: {
117
- url: `/sites/{siteId}/users?${ query.toString() }`,
118
- method: 'get',
119
- },
120
- });
121
-
122
- const { ok, data, error } = response;
123
- if (!ok) {
124
- logDeep({ error });
125
- return { ok: false, error };
126
- }
127
-
128
- const pageUsers = data?.users?.user ?? [];
129
- users.push(...pageUsers);
130
-
131
- const totalAvailable = Number(data?.pagination?.totalAvailable ?? pageUsers.length);
132
- if (users.length >= totalAvailable || pageUsers.length === 0) {
133
- break;
134
- }
135
-
136
- pageNumber += 1;
137
- }
35
+ },
36
+ perPage,
37
+ resultsKey: 'users.user',
38
+ fetchClient,
39
+ ...getterOptions,
40
+ });
41
+ };
138
42
 
139
- return {
140
- ok: true,
141
- data: users,
142
- };
43
+ const funcApiConfig = {
44
+ argsWarden,
143
45
  };
144
46
 
145
47
  module.exports = {
146
48
  tableauUsersGet,
147
- tableauClient,
49
+ funcApiConfig,
148
50
  };
149
51
 
150
52
  /*
151
- curl -X POST "http://localhost:8000/tableauUsersGet"
152
-
153
- curl -X POST "http://localhost:8000/tableauUsersGet"
154
- -d '{ "filter": "siteRole:eq:Creator" }'
53
+ curl -X POST "http://localhost:8000/tableauUsersGet" \
54
+ -H "Content-Type: application/json" \
55
+ -d '{
56
+ "credsPayload": { "credsPath": "tableau" }
57
+ }'
58
+
59
+ curl -X POST "http://localhost:8000/tableauUsersGet" \
60
+ -H "Content-Type: application/json" \
61
+ -d '{
62
+ "credsPayload": { "credsPath": "tableau" },
63
+ "options": {
64
+ "filter": "siteRole:eq:Creator"
65
+ }
66
+ }'
155
67
  */
@@ -2,6 +2,6 @@
2
2
 
3
3
  - [Storefront API (v2)](https://tagalys.notion.site/Storefront-API-v2-20eacdd38c2080d58d3fd0cf6f24e435)
4
4
 
5
- Region-specific HTTPS origins (`https://api-r{n}.tagalys.com`) with REST-style JSON under `/v2`. Storefront reads use GET; analytics ingest uses `POST /v2/analytics/events` with a JSON body. Browser requests authenticate with the `shop_id` query param (the shops `*.myshopify.com` domain). Server-side integrations should pass `api_key`.
5
+ Region-specific HTTPS origins (`https://api-r{n}.tagalys.com`) with REST-style JSON under `/v2`. Storefront reads use GET; analytics ingest uses `POST /v2/analytics/events` with a JSON body. Browser requests authenticate with the `shop_id` query param (the shop's `*.myshopify.com` domain). Server-side integrations should also pass an API key -- the published docs name this param `storefront_api_key`, but live testing against this account found `api_key` is what actually authenticates (see tagalys.utils.js).
6
6
 
7
- Endpoints: `GET /v2/collections/:collection_id`, `GET /v2/search`, `GET /v2/search_suggestions`, `GET /v2/popular_searches`, `GET /v2/recommendations/:recommendation_id`, `POST /v2/analytics/events`. Collections and search support pagination (`page`, `per_page`, capped at 10,000 products), sorting (`sort`, `include[]=sort_options`), filtering (`filter[...]`, `include[]=filters`), and scope (`scope[...]`). Use `include[]=products` or `include[]=product_ids` to control product payloads. Optional request context on collections, search, and recommendations: `country`, `language`, `segment_tag`. Errors return JSON with `error.type`, `error.code`, and `error.message`.
7
+ Endpoints: `GET /v2/collections/:collection_id`, `GET /v2/search`, `GET /v2/search_suggestions`, `GET /v2/popular_searches`, `GET /v2/recommendations/:recommendation_id`, `POST /v2/analytics/events`. Collections and search support pagination (`page`, `per_page`, capped at 10,000 products), sorting (`sort`, `include[]=sort_options`), filtering (`filter[...]`, `include[]=filters`), and scope (`scope[...]`, a fixed server-side constraint rather than a shopper-facing facet). Collections also support `banner_positions` to reduce returned products around merchandising banners. Use `include[]=products` or `include[]=product_ids` to control product payloads. Optional request context on collections, search, and recommendations: `country`, `language`, `segment_tag`. Search and search_suggestions can return a top-level `redirect_url` for merchant-configured query redirects, which takes precedence over the rest of the response. Errors return JSON with `error.type`, `error.code`, and `error.message`.
@@ -0,0 +1,17 @@
1
+ const DEFAULT_INCLUDE = ['products', 'total_count'];
2
+
3
+ // "Pagination is restricted to the top 10,000 products."
4
+ const MAX_PAGINATION_PRODUCTS = 10000;
5
+
6
+ // "up to 3 are supported" (recommendations :product_ids param)
7
+ const MAX_RECOMMENDATION_PRODUCT_IDS = 3;
8
+
9
+ // "Returns at most 10 queries" (GET /v2/popular_searches)
10
+ const MAX_POPULAR_SEARCHES = 10;
11
+
12
+ module.exports = {
13
+ DEFAULT_INCLUDE,
14
+ MAX_PAGINATION_PRODUCTS,
15
+ MAX_RECOMMENDATION_PRODUCT_IDS,
16
+ MAX_POPULAR_SEARCHES,
17
+ };
@@ -0,0 +1,125 @@
1
+ // https://tagalys.notion.site/Storefront-API-v2-20eacdd38c2080d58d3fd0cf6f24e435
2
+
3
+ const { resolveCreds } = require('../pipelineSteps');
4
+ const {
5
+ FetchClient,
6
+ fetchClientCommonSteps,
7
+ } = require('../utils');
8
+
9
+ // Recursively flattens nested params into Rails/PHP-style bracket query
10
+ // params, e.g. { filter: { color: ['red'] } } -> filter[color][]=red
11
+ // and { filter: { price: { selected_min: 100 } } } -> filter[price][selected_min]=100
12
+ // This also covers the search_suggestions `sections[section_id][*]` shape,
13
+ // e.g. { sections: { products: { count: 6 } } } -> sections[products][count]=6
14
+ const appendParams = (searchParams, key, value) => {
15
+ if (value === undefined || value === null) {
16
+ return;
17
+ }
18
+ if (Array.isArray(value)) {
19
+ value.forEach((item) => appendParams(searchParams, `${ key }[]`, item));
20
+ } else if (typeof value === 'object') {
21
+ Object.entries(value).forEach(([subKey, subValue]) => {
22
+ appendParams(searchParams, `${ key }[${ subKey }]`, subValue);
23
+ });
24
+ } else {
25
+ searchParams.append(key, value);
26
+ }
27
+ };
28
+
29
+ // Request context (country, language, segmentTag) is supported by the
30
+ // collections, search and recommendations endpoints per the docs. Callers
31
+ // pass these via `context` (like `apiVersion` in the shopify client),
32
+ // rather than merging them into `query` themselves, so the shared client
33
+ // applies them consistently across every endpoint that uses it.
34
+ const useRequestContextParams = async (state) => {
35
+ const { requestPayload, context } = state;
36
+ const { country, language, segmentTag } = context;
37
+
38
+ if (!country && !language && !segmentTag) {
39
+ return {};
40
+ }
41
+
42
+ return {
43
+ requestPayload: {
44
+ ...requestPayload,
45
+ query: {
46
+ ...requestPayload.query,
47
+ ...(country ? { country } : {}),
48
+ ...(language ? { language } : {}),
49
+ ...(segmentTag ? { segment_tag: segmentTag } : {}),
50
+ },
51
+ },
52
+ };
53
+ };
54
+
55
+ // Base URL is region-specific per account (e.g. https://api-r1.tagalys.com),
56
+ // so per AGENTS.md it's resolved from creds rather than tagalys.constants.js.
57
+ const useUrlAndQuery = async (state) => {
58
+ const { requestPayload, context } = state;
59
+ const { creds } = context;
60
+
61
+ const {
62
+ BASE_URL,
63
+ STORE_HANDLE,
64
+ STOREFRONT_API_KEY,
65
+ } = creds;
66
+
67
+ const searchParams = new URLSearchParams();
68
+ searchParams.append('shop_id', `${ STORE_HANDLE }.myshopify.com`);
69
+ if (STOREFRONT_API_KEY) {
70
+ // NOTE: the published docs call this param `storefront_api_key`, but a
71
+ // live request with that name returned `api_key_invalid`. `api_key`
72
+ // is what actually authenticates -- trusting the working behaviour
73
+ // over the doc text here. Revisit if Tagalys ships the documented name.
74
+ searchParams.append('api_key', STOREFRONT_API_KEY);
75
+ }
76
+ Object.entries(requestPayload.query || {}).forEach(([key, value]) => {
77
+ appendParams(searchParams, key, value);
78
+ });
79
+
80
+ return {
81
+ requestPayload: {
82
+ ...requestPayload,
83
+ url: `${ BASE_URL }${ requestPayload.url }?${ searchParams.toString() }`,
84
+ headers: {
85
+ Accept: 'application/json',
86
+ ...requestPayload.headers,
87
+ },
88
+ },
89
+ };
90
+ };
91
+
92
+ // A configured redirect takes precedence over the rest of the response --
93
+ // surface it plainly rather than making callers dig for it. Only /v2/search
94
+ // and /v2/search_suggestions ever populate `redirect_url`, so this is a
95
+ // no-op for every other endpoint on the shared client.
96
+ const useRedirectResponse = async (state) => {
97
+ const { response } = state;
98
+
99
+ if (!response?.ok || !response?.data?.redirect_url) {
100
+ return {};
101
+ }
102
+
103
+ return {
104
+ response: {
105
+ redirected: true,
106
+ redirectUrl: response.data.redirect_url,
107
+ },
108
+ };
109
+ };
110
+
111
+ const tagalysClient = new FetchClient({
112
+ pipeline: [
113
+ resolveCreds,
114
+ useRequestContextParams,
115
+ useUrlAndQuery,
116
+ 'fetch',
117
+ fetchClientCommonSteps.exitEarlyOnNotOk,
118
+ useRedirectResponse,
119
+ ],
120
+ });
121
+
122
+ module.exports = {
123
+ tagalysClient,
124
+ appendParams,
125
+ };
@@ -0,0 +1,125 @@
1
+ // https://tagalys.notion.site/Storefront-API-v2-20eacdd38c2080d58d3fd0cf6f24e435
2
+
3
+ const { credsValidator } = require('../validators');
4
+ const { ArgsWarden, actionSingleOrMultiple, everyIfArray, valueProvided, logDeep } = require('../utils');
5
+ const { tagalysClient } = require('../tagalys/tagalys.utils');
6
+
7
+ // Supported `type` values and their `payload` shape:
8
+ // product_viewed { productId }
9
+ // product_added_to_cart { productId, quantity }
10
+ // checkout_completed { orderId, lineItems: [{ productId, quantity }] }
11
+ // search_results_viewed { query, productIds, page, totalCount, queryHandling?, sortedBy?, filteredBy? }
12
+ // collection_viewed { collectionId, productIds?, page?, totalCount?, sortedBy?, filteredBy? }
13
+ // recommendations_viewed { id, recommendedProductIds, sourceProductIds? (required when `id` is contextual to a product) }
14
+ const eventPayloadValidator = (eventPayload) => {
15
+ return valueProvided(eventPayload?.type)
16
+ && valueProvided(eventPayload?.payload)
17
+ && valueProvided(eventPayload?.context?.deviceId)
18
+ && valueProvided(eventPayload?.context?.visitId);
19
+ };
20
+
21
+ const argsWarden = new ArgsWarden([
22
+ ['credsPayload', credsValidator],
23
+ ['eventPayload', (eventPayload) => everyIfArray(eventPayloadValidator, eventPayload)],
24
+ ]);
25
+
26
+ const tagalysAnalyticsEventSendSingle = async (
27
+ credsPayload,
28
+ eventPayload,
29
+ ) => {
30
+ const { type, payload, context } = eventPayload;
31
+ const {
32
+ deviceId,
33
+ visitId,
34
+ userId,
35
+ country,
36
+ language,
37
+ segmentTag,
38
+ apiClientName,
39
+ apiClientVersion,
40
+ } = context;
41
+
42
+ const response = await tagalysClient.fetch({
43
+ context: {
44
+ credsPayload,
45
+ },
46
+ requestPayload: {
47
+ url: '/v2/analytics/events',
48
+ method: 'post',
49
+ body: {
50
+ type,
51
+ payload,
52
+ context: {
53
+ device_id: deviceId,
54
+ visit_id: visitId,
55
+ ...(userId ? { user_id: userId } : {}),
56
+ ...(country ? { country } : {}),
57
+ ...(language ? { language } : {}),
58
+ ...(segmentTag ? { segment_tag: segmentTag } : {}),
59
+ ...((apiClientName || apiClientVersion) ? {
60
+ api_client: {
61
+ ...(apiClientName ? { name: apiClientName } : {}),
62
+ ...(apiClientVersion ? { version: apiClientVersion } : {}),
63
+ },
64
+ } : {}),
65
+ },
66
+ },
67
+ },
68
+ });
69
+
70
+ const { ok, error } = response;
71
+ if (!ok) {
72
+ logDeep({ error });
73
+ }
74
+
75
+ return response;
76
+ };
77
+
78
+ const tagalysAnalyticsEventSend = async (
79
+ credsPayload,
80
+ eventPayload,
81
+ {
82
+ queueRunOptions,
83
+ } = {},
84
+ ) => {
85
+
86
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
87
+ credsPayload,
88
+ eventPayload,
89
+ });
90
+ if (rejectResponse) {
91
+ return rejectResponse;
92
+ }
93
+
94
+ return actionSingleOrMultiple(
95
+ eventPayload,
96
+ tagalysAnalyticsEventSendSingle,
97
+ (eventPayloadItem) => ({
98
+ args: [credsPayload, eventPayloadItem],
99
+ }),
100
+ {
101
+ ...(queueRunOptions ? { queueRunOptions } : {}),
102
+ },
103
+ );
104
+ };
105
+
106
+ const funcApiConfig = {
107
+ argsWarden,
108
+ };
109
+
110
+ module.exports = {
111
+ tagalysAnalyticsEventSend,
112
+ funcApiConfig,
113
+ };
114
+
115
+ /*
116
+ curl -X POST "http://localhost:8000/tagalysAnalyticsEventSend" \
117
+ -d '{
118
+ "credsPayload": { "credsPath": "tagalys.au" },
119
+ "eventPayload": {
120
+ "type": "product_viewed",
121
+ "payload": { "productId": "7286848028804" },
122
+ "context": { "deviceId": "d123", "visitId": "v123" }
123
+ }
124
+ }'
125
+ */
@@ -0,0 +1,100 @@
1
+ // https://tagalys.notion.site/Storefront-API-v2-20eacdd38c2080d58d3fd0cf6f24e435
2
+
3
+ const { credsValidator } = require('../validators');
4
+ const { ArgsWarden, actionSingleOrMultiple, logDeep } = require('../utils');
5
+ const { DEFAULT_INCLUDE } = require('../tagalys/tagalys.constants');
6
+ const { tagalysClient } = require('../tagalys/tagalys.utils');
7
+
8
+ const argsWarden = new ArgsWarden([
9
+ ['credsPayload', credsValidator],
10
+ ['collectionId'],
11
+ ]);
12
+
13
+ const tagalysCollectionGetSingle = async (
14
+ credsPayload,
15
+ collectionId,
16
+ {
17
+ include = DEFAULT_INCLUDE, // e.g. ['products', 'filters', 'sort_options', 'total_count']
18
+ filter, // e.g. { color: ['red'], price: { selected_min: 100, selected_max: 200 } }
19
+ scope, // e.g. { gender: ['female'] }
20
+ sort, // e.g. 'price-asc'
21
+ page,
22
+ perPage,
23
+ bannerPositions, // { source: 'dashboard' | 'custom' | 'none', fixed: [4, 6], repeating: { every: 16, at: [5] } }
24
+ country,
25
+ language,
26
+ segmentTag,
27
+ } = {},
28
+ ) => {
29
+ const response = await tagalysClient.fetch({
30
+ context: {
31
+ credsPayload,
32
+ country,
33
+ language,
34
+ segmentTag,
35
+ },
36
+ requestPayload: {
37
+ url: `/v2/collections/${ collectionId }`,
38
+ method: 'get',
39
+ query: {
40
+ include,
41
+ ...(filter ? { filter } : {}),
42
+ ...(scope ? { scope } : {}),
43
+ ...(sort ? { sort } : {}),
44
+ ...(page ? { page } : {}),
45
+ ...(perPage ? { per_page: perPage } : {}),
46
+ ...(bannerPositions ? { banner_positions: bannerPositions } : {}),
47
+ },
48
+ },
49
+ });
50
+
51
+ const { ok, error } = response;
52
+ if (!ok) {
53
+ logDeep({ error });
54
+ }
55
+
56
+ return response;
57
+ };
58
+
59
+ const tagalysCollectionGet = async (
60
+ credsPayload,
61
+ collectionId,
62
+ {
63
+ queueRunOptions,
64
+ ...options
65
+ } = {},
66
+ ) => {
67
+
68
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
69
+ credsPayload,
70
+ collectionId,
71
+ });
72
+ if (rejectResponse) {
73
+ return rejectResponse;
74
+ }
75
+
76
+ return actionSingleOrMultiple(
77
+ collectionId,
78
+ tagalysCollectionGetSingle,
79
+ (collectionIdItem) => ({
80
+ args: [credsPayload, collectionIdItem, options],
81
+ }),
82
+ {
83
+ ...(queueRunOptions ? { queueRunOptions } : {}),
84
+ },
85
+ );
86
+ };
87
+
88
+ const funcApiConfig = {
89
+ argsWarden,
90
+ };
91
+
92
+ module.exports = {
93
+ tagalysCollectionGet,
94
+ funcApiConfig,
95
+ };
96
+
97
+ /*
98
+ curl -X POST "http://localhost:8000/tagalysCollectionGet" \
99
+ -d '{ "credsPayload": { "credsPath": "tagalys.au" }, "collectionId": "123456789" }'
100
+ */
@@ -0,0 +1,60 @@
1
+ // https://tagalys.notion.site/Storefront-API-v2-20eacdd38c2080d58d3fd0cf6f24e435
2
+
3
+ const { credsValidator } = require('../validators');
4
+ const { ArgsWarden, logDeep } = require('../utils');
5
+ const { tagalysClient } = require('../tagalys/tagalys.utils');
6
+
7
+ const argsWarden = new ArgsWarden([
8
+ ['credsPayload', credsValidator],
9
+ ]);
10
+
11
+ // Returns at most 10 queries. When the store is configured for country-based
12
+ // availability, `country` filters the response (see the docs).
13
+ const tagalysPopularSearchesGet = async (
14
+ credsPayload,
15
+ {
16
+ country,
17
+ } = {},
18
+ ) => {
19
+ const rejectResponse = await argsWarden.responseIfRejectingArgs({
20
+ credsPayload,
21
+ });
22
+ if (rejectResponse) {
23
+ return rejectResponse;
24
+ }
25
+
26
+ const response = await tagalysClient.fetch({
27
+ context: {
28
+ credsPayload,
29
+ },
30
+ requestPayload: {
31
+ url: '/v2/popular_searches',
32
+ method: 'get',
33
+ query: {
34
+ ...(country ? { country } : {}),
35
+ },
36
+ },
37
+ });
38
+
39
+ const { ok, data, error } = response;
40
+ if (!ok) {
41
+ logDeep({ error });
42
+ return { ok: false, error };
43
+ }
44
+
45
+ return { ok: true, data };
46
+ };
47
+
48
+ const funcApiConfig = {
49
+ argsWarden,
50
+ };
51
+
52
+ module.exports = {
53
+ tagalysPopularSearchesGet,
54
+ funcApiConfig,
55
+ };
56
+
57
+ /*
58
+ curl -X POST "http://localhost:8000/tagalysPopularSearchesGet" \
59
+ -d '{ "credsPayload": { "credsPath": "tagalys.au" } }'
60
+ */