├── .gitignore ├── .prettierrc ├── README.md ├── metadata.yaml ├── LICENSE ├── template.js └── template.tpl /.gitignore: -------------------------------------------------------------------------------- 1 | server-gtm-sandboxed-apis.d.ts -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "none" 4 | } 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Client for Google Tag Manager Server Side 2 | 3 | Data Client developed for receiving requests from [Data Tag](https://github.com/stape-io/data-tag) placed inside the Google Tag Manager Web Container, but it can also receive any request and map it to the Event Data inside the Google Tag Manager Server Side container. 4 | 5 | ## Useful resources 6 | 7 | - https://stape.io/solutions/data-tag-client 8 | - https://stape.io/blog/sending-data-from-google-tag-manager-web-container-to-the-server-container 9 | - https://stape.io/blog/send-datalayer-push-from-server-gtm-to-web-gtm 10 | 11 | ## Open Source 12 | 13 | Data Client for Google Tag Manager Server Side is developed and maintained by [Stape Team](https://stape.io/) under the Apache 2.0 license. 14 | -------------------------------------------------------------------------------- /metadata.yaml: -------------------------------------------------------------------------------- 1 | homepage: 'https://stape.io/' 2 | documentation: 'https://github.com/stape-io/data-client' 3 | versions: 4 | - sha: 7c813f3d19305a5b54e8c122e4c42728b10fbccf 5 | changeNotes: |2 6 | Fixed the Client ID auto generation when the _dcid cookie does not exist and multiple requests are sent at once. 7 | Make sure to update the Data Tag in GTM Web as well. 8 | - sha: 3992d61eb8bc9f0314e9501ed6f6a86fd1671e8a 9 | changeNotes: |2 10 | Fix the return status when there is no default value to be returned. 11 | Fix the event when processing the container takes more than 5 seconds to run the event. 12 | - sha: 2cd52aa8ece4014cb0d02674c0ef6d40ee479554 13 | changeNotes: Add x-stape-app-version to Access-Control-Allow-Headers headers. 14 | - sha: 953bf24c77b68e708fee1e953eea31303bf1fde1 15 | changeNotes: Fix for timestamp and unique_event_id override. 16 | - sha: a9fb729fd9eed2013188c00e820fa81aa78e71c1 17 | changeNotes: Fixed location response header bug. 18 | - sha: e31d2f39c10285cbc5169e349c473f73e4668692 19 | changeNotes: Added support for x-www-form-urlencoded. 20 | - sha: 4d9f4d4fbded5414cb091efac70224d31c522e5c 21 | changeNotes: Fix user address data. 22 | - sha: 905af50fe8eb5f61e58a6d04c33fd6faf01e7f98 23 | changeNotes: user_data persistence fix. 24 | - sha: e11b7b68f8160fd6cc6d210daef907e25b4670cf 25 | changeNotes: Fix issue with gAds user data. 26 | - sha: f6511e191159a89583452d7ff2e97700069cec1c 27 | changeNotes: Add Matomo support. 28 | - sha: 199507c3b10f3acb51c6ce307129792fb07d9700 29 | changeNotes: Fix issue with rights. 30 | - sha: cb233b88ee98f576d2d27fa4c06234cecb66b268 31 | changeNotes: Accept multiple events. 32 | - sha: 42a2c80254ef261b4c79e4414ff4525a239856af 33 | changeNotes: Allow to configure custom redirects. 34 | - sha: 448e609ee33eedbfaa2070d70eb23b8776f95fe3 35 | changeNotes: Add unique_event_id to eventData. 36 | - sha: 91da5a8f79c50216ecd882a1e7a478520b418e37 37 | changeNotes: Update EE parsing. 38 | - sha: 65143e70107a90b10297d080d342b7056a74eefd 39 | changeNotes: Add additional data for EE events. 40 | - sha: fb78186e3fa6f49bde7a32b9e4714eaf4d1cce86 41 | changeNotes: Add response settings. 42 | - sha: 7ff22a33ef4eb76b0311dd45cd40e92ab7068888 43 | changeNotes: Update cookie storing. 44 | - sha: f0e02106d0c538455c4b959051066fbb59f7afa0 45 | changeNotes: Add Data Tag dtcd parameter support. 46 | - sha: a88f51afe94db1f5e5a97ebe5cf251fc0cb444c9 47 | changeNotes: Add client_id generation functionality. 48 | - sha: 28b7b5dc4dfca58555fd15fff3fefe18b7b49762 49 | changeNotes: Add data store functionality. 50 | - sha: 713fbe32cc954debebd9f145de8c9224ce75e110 51 | changeNotes: Add FPIDP cookie. 52 | - sha: 3bc72ee6f317905f2356e452014ac88f42336c03 53 | changeNotes: Move from gtm-server to stape. 54 | - sha: 5ae9e0c010cf4e4c0c4d1dcc70fac5c28dbe1a66 55 | changeNotes: Do not run container on option request. 56 | - sha: 7c3b0f7ff92880ce3a83dbf5f4eca315e468e2a4 57 | changeNotes: Move transformation logic to the web. 58 | - sha: e927adb13b807eb375c07553da418f592be51e1e 59 | changeNotes: Initial release. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Stape 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /template.js: -------------------------------------------------------------------------------- 1 | const returnResponse = require('returnResponse'); 2 | const runContainer = require('runContainer'); 3 | const setResponseHeader = require('setResponseHeader'); 4 | const setResponseStatus = require('setResponseStatus'); 5 | const setResponseBody = require('setResponseBody'); 6 | const JSON = require('JSON'); 7 | const fromBase64 = require('fromBase64'); 8 | const getTimestampMillis = require('getTimestampMillis'); 9 | const getCookieValues = require('getCookieValues'); 10 | const getRequestBody = require('getRequestBody'); 11 | const getRequestMethod = require('getRequestMethod'); 12 | const getRequestHeader = require('getRequestHeader'); 13 | const getRequestPath = require('getRequestPath'); 14 | const getRequestQueryParameters = require('getRequestQueryParameters'); 15 | const makeInteger = require('makeInteger'); 16 | const getRemoteAddress = require('getRemoteAddress'); 17 | const setCookie = require('setCookie'); 18 | const setPixelResponse = require('setPixelResponse'); 19 | const generateRandom = require('generateRandom'); 20 | const computeEffectiveTldPlusOne = require('computeEffectiveTldPlusOne'); 21 | const getRequestQueryParameter = require('getRequestQueryParameter'); 22 | const getType = require('getType'); 23 | const decodeUriComponent = require('decodeUriComponent'); 24 | const createRegex = require('createRegex'); 25 | const makeString = require('makeString'); 26 | const Object = require('Object'); 27 | 28 | /*============================================================================== 29 | ==============================================================================*/ 30 | 31 | const requestMethod = getRequestMethod(); 32 | const path = getRequestPath(); 33 | let isClientUsed = false; 34 | let isEventModelsWrappedInArray = false; 35 | 36 | if (path === '/data') { 37 | runClient(); 38 | } 39 | 40 | if (data.path && !isClientUsed) { 41 | for (let key in data.path) { 42 | if (!isClientUsed && data.path[key].path === path) { 43 | runClient(); 44 | } 45 | } 46 | } 47 | 48 | /*============================================================================== 49 | Vendor related functions 50 | ==============================================================================*/ 51 | 52 | function runClient() { 53 | isClientUsed = true; 54 | require('claimRequest')(); 55 | 56 | if (requestMethod === 'OPTIONS') { 57 | setCommonResponseHeaders(200); 58 | returnResponse(); 59 | return; 60 | } 61 | const baseEventModel = getBaseEventModelWithQueryParameters(); 62 | let eventModels = getEventModels(baseEventModel); 63 | const clientId = getClientId(eventModels); 64 | eventModels = eventModels.map((eventModel) => { 65 | eventModel = addRequiredParametersToEventModel(eventModel); 66 | eventModel = addCommonParametersToEventModel(eventModel); 67 | eventModel = addClientIdToEventModel(eventModel, clientId); 68 | if (eventModel._dcid_temp) Object.delete(eventModel, '_dcid_temp'); 69 | return eventModel; 70 | }); 71 | 72 | storeClientId(eventModels[0]); 73 | exposeFPIDCookie(eventModels[0]); 74 | prolongDataTagCookies(eventModels[0]); 75 | const responseStatusCode = makeInteger(data.responseStatusCode || 200); 76 | setCommonResponseHeaders(responseStatusCode); 77 | 78 | let counter = 0; 79 | eventModels.forEach((event) => { 80 | runContainer(event, () => { 81 | if (++counter === eventModels.length) { 82 | switch (responseStatusCode) { 83 | case 200: 84 | case 201: 85 | if (requestMethod === 'POST' || data.responseBodyGet) { 86 | prepareResponseBody(eventModels); 87 | } else { 88 | setPixelResponse(); 89 | } 90 | break; 91 | case 301: 92 | case 302: 93 | setRedirectLocation(); 94 | break; 95 | case 403: 96 | case 404: 97 | setClientErrorResponseMessage(); 98 | break; 99 | } 100 | 101 | returnResponse(); 102 | } 103 | }); 104 | }); 105 | } 106 | 107 | function addCommonParametersToEventModel(eventModel) { 108 | if (!eventModel.ip_override) { 109 | if (eventModel.ip) eventModel.ip_override = eventModel.ip; 110 | else if (eventModel.ipOverride) 111 | eventModel.ip_override = eventModel.ipOverride; 112 | else eventModel.ip_override = getRemoteAddress(); 113 | } 114 | 115 | if (!eventModel.user_agent) { 116 | if (eventModel.userAgent) eventModel.user_agent = eventModel.userAgent; 117 | else if (getRequestHeader('User-Agent')) 118 | eventModel.user_agent = getRequestHeader('User-Agent'); 119 | } 120 | 121 | if (!eventModel.language) { 122 | const acceptLanguageHeader = getRequestHeader('Accept-Language'); 123 | 124 | if (acceptLanguageHeader) { 125 | eventModel.language = acceptLanguageHeader 126 | .split(';')[0] 127 | .substring(0, 2) 128 | .toLowerCase(); 129 | } 130 | } 131 | 132 | if (!eventModel.page_hostname) { 133 | if (eventModel.pageHostname) 134 | eventModel.page_hostname = eventModel.pageHostname; 135 | else if (eventModel.hostname) 136 | eventModel.page_hostname = eventModel.hostname; 137 | } 138 | 139 | if (!eventModel.page_location) { 140 | if (eventModel.pageLocation) 141 | eventModel.page_location = eventModel.pageLocation; 142 | else if (eventModel.url) eventModel.page_location = eventModel.url; 143 | else if (eventModel.href) eventModel.page_location = eventModel.href; 144 | } 145 | 146 | if (!eventModel.page_referrer) { 147 | if (eventModel.pageReferrer) 148 | eventModel.page_referrer = eventModel.pageReferrer; 149 | else if (eventModel.referrer) 150 | eventModel.page_referrer = eventModel.referrer; 151 | else if (eventModel.urlref) eventModel.page_referrer = eventModel.urlref; 152 | } 153 | 154 | if (!eventModel.value && eventModel.e_v) eventModel.value = eventModel.e_v; 155 | 156 | if (getType(eventModel.items) === 'array' && eventModel.items.length) { 157 | const firstItem = eventModel.items[0]; 158 | if (!eventModel.currency && firstItem.currency) 159 | eventModel.currency = firstItem.currency; 160 | if (eventModel.items.length === 1) { 161 | if (!eventModel.item_id && firstItem.item_id) 162 | eventModel.item_id = firstItem.item_id; 163 | if (!eventModel.item_name && firstItem.item_name) 164 | eventModel.item_name = firstItem.item_name; 165 | if (!eventModel.item_brand && firstItem.item_brand) 166 | eventModel.item_brand = firstItem.item_brand; 167 | if (!eventModel.item_quantity && firstItem.quantity) 168 | eventModel.item_quantity = firstItem.quantity; 169 | if (!eventModel.item_category && firstItem.item_category) 170 | eventModel.item_category = firstItem.item_category; 171 | if (!eventModel.item_price && firstItem.price) 172 | eventModel.item_price = firstItem.price; 173 | } 174 | if (!eventModel.value) { 175 | const valueFromItems = eventModel.items.reduce((acc, item) => { 176 | if (!item.price) return acc; 177 | const quantity = item.quantity ? item.quantity : 1; 178 | return acc + quantity * item.price; 179 | }, 0); 180 | if (valueFromItems) eventModel.value = valueFromItems; 181 | } 182 | } 183 | 184 | const ecommerceAction = getEcommerceAction(eventModel); 185 | 186 | if (ecommerceAction) { 187 | if (!eventModel['x-ga-mp1-pa']) eventModel['x-ga-mp1-pa'] = ecommerceAction; 188 | 189 | if ( 190 | ecommerceAction === 'purchase' && 191 | eventModel.ecommerce.purchase.actionField 192 | ) { 193 | if (!eventModel['x-ga-mp1-tr']) 194 | eventModel['x-ga-mp1-tr'] = 195 | eventModel.ecommerce.purchase.actionField.revenue; 196 | if (!eventModel.revenue) 197 | eventModel.revenue = eventModel.ecommerce.purchase.actionField.revenue; 198 | if (!eventModel.affiliation) 199 | eventModel.affiliation = 200 | eventModel.ecommerce.purchase.actionField.affiliation; 201 | if (!eventModel.tax) 202 | eventModel.tax = eventModel.ecommerce.purchase.actionField.tax; 203 | if (!eventModel.shipping) 204 | eventModel.shipping = 205 | eventModel.ecommerce.purchase.actionField.shipping; 206 | if (!eventModel.coupon) 207 | eventModel.coupon = eventModel.ecommerce.purchase.actionField.coupon; 208 | if (!eventModel.transaction_id) 209 | eventModel.transaction_id = 210 | eventModel.ecommerce.purchase.actionField.id; 211 | } 212 | } 213 | 214 | if (!eventModel.page_encoding && eventModel.pageEncoding) 215 | eventModel.page_encoding = eventModel.pageEncoding; 216 | if (!eventModel.page_path && eventModel.pagePath) 217 | eventModel.page_path = eventModel.pagePath; 218 | if (!eventModel.page_title && eventModel.pageTitle) 219 | eventModel.page_title = eventModel.pageTitle; 220 | if (!eventModel.screen_resolution && eventModel.screenResolution) 221 | eventModel.screen_resolution = eventModel.screenResolution; 222 | if (!eventModel.viewport_size && eventModel.viewportSize) 223 | eventModel.viewport_size = eventModel.viewportSize; 224 | if (!eventModel.user_id && eventModel.userId) 225 | eventModel.user_id = eventModel.userId; 226 | 227 | if (!eventModel.user_data) { 228 | let userData = {}; 229 | let userAddressData = {}; 230 | 231 | if (!userData.email_address) { 232 | if (eventModel.userEmail) userData.email_address = eventModel.userEmail; 233 | else if (eventModel.email_address) 234 | userData.email_address = eventModel.email_address; 235 | else if (eventModel.email) userData.email_address = eventModel.email; 236 | else if (eventModel.mail) userData.email_address = eventModel.mail; 237 | } 238 | 239 | if (!userData.phone_number) { 240 | if (eventModel.userPhoneNumber) 241 | userData.phone_number = eventModel.userPhoneNumber; 242 | else if (eventModel.phone_number) 243 | userData.phone_number = eventModel.phone_number; 244 | else if (eventModel.phoneNumber) 245 | userData.phone_number = eventModel.phoneNumber; 246 | else if (eventModel.phone) userData.phone_number = eventModel.phone; 247 | } 248 | 249 | if (!userAddressData.street && eventModel.street) 250 | userAddressData.street = eventModel.street; 251 | if (!userAddressData.city && eventModel.city) 252 | userAddressData.city = eventModel.city; 253 | if (!userAddressData.region && eventModel.region) 254 | userAddressData.region = eventModel.region; 255 | if (!userAddressData.country && eventModel.country) 256 | userAddressData.country = eventModel.country; 257 | 258 | if (!userAddressData.first_name) { 259 | if (eventModel.userFirstName) 260 | userAddressData.first_name = eventModel.userFirstName; 261 | else if (eventModel.first_name) 262 | userAddressData.first_name = eventModel.first_name; 263 | else if (eventModel.firstName) 264 | userAddressData.first_name = eventModel.firstName; 265 | else if (eventModel.name) userAddressData.first_name = eventModel.name; 266 | } 267 | 268 | if (!userAddressData.last_name) { 269 | if (eventModel.userLastName) 270 | userAddressData.last_name = eventModel.userLastName; 271 | else if (eventModel.last_name) 272 | userAddressData.last_name = eventModel.last_name; 273 | else if (eventModel.lastName) 274 | userAddressData.last_name = eventModel.lastName; 275 | else if (eventModel.surname) 276 | userAddressData.last_name = eventModel.surname; 277 | else if (eventModel.family_name) 278 | userAddressData.last_name = eventModel.family_name; 279 | else if (eventModel.familyName) 280 | userAddressData.last_name = eventModel.familyName; 281 | } 282 | 283 | if (!userAddressData.region) { 284 | if (eventModel.region) userAddressData.region = eventModel.region; 285 | else if (eventModel.state) userAddressData.region = eventModel.state; 286 | } 287 | 288 | if (!userAddressData.postal_code) { 289 | if (eventModel.postal_code) 290 | userAddressData.postal_code = eventModel.postal_code; 291 | else if (eventModel.postalCode) 292 | userAddressData.postal_code = eventModel.postalCode; 293 | else if (eventModel.zip) userAddressData.postal_code = eventModel.zip; 294 | } 295 | 296 | if (getObjectLength(userAddressData) !== 0) { 297 | userData.address = userAddressData; 298 | } 299 | 300 | if (!eventModel.user_data && getObjectLength(userData) !== 0) { 301 | eventModel.user_data = userData; 302 | } 303 | } 304 | 305 | return eventModel; 306 | } 307 | 308 | function getBaseEventModelWithQueryParameters() { 309 | const requestQueryParameters = getRequestQueryParameters(); 310 | const eventModel = {}; 311 | 312 | if (requestQueryParameters) { 313 | for (let queryParameterKey in requestQueryParameters) { 314 | if ( 315 | (queryParameterKey === 'dtcd' || queryParameterKey === 'dtdc') && 316 | requestMethod === 'GET' 317 | ) { 318 | let dt = 319 | queryParameterKey === 'dtcd' 320 | ? JSON.parse(requestQueryParameters[queryParameterKey]) 321 | : JSON.parse(fromBase64(requestQueryParameters[queryParameterKey])); 322 | 323 | for (let dtKey in dt) { 324 | eventModel[dtKey] = dt[dtKey]; 325 | } 326 | } else { 327 | eventModel[queryParameterKey] = 328 | requestQueryParameters[queryParameterKey]; 329 | } 330 | } 331 | } 332 | 333 | return eventModel; 334 | } 335 | 336 | function addClientIdToEventModel(eventModel, clientId) { 337 | eventModel.client_id = clientId; 338 | return eventModel; 339 | } 340 | 341 | function prolongDataTagCookies(eventModel) { 342 | if (data.prolongCookies) { 343 | let stapeData = getCookieValues('stape'); 344 | 345 | if (stapeData.length) { 346 | setCookie('stape', stapeData[0], { 347 | domain: 'auto', 348 | path: '/', 349 | samesite: getCookieType(eventModel), 350 | secure: true, 351 | 'max-age': 63072000, // 2 years 352 | httpOnly: false 353 | }); 354 | } 355 | } 356 | } 357 | 358 | function addRequiredParametersToEventModel(eventModel) { 359 | if (!eventModel.event_name) { 360 | let eventName = 'Data'; 361 | 362 | if (eventModel.eventName) eventName = eventModel.eventName; 363 | else if (eventModel.event) eventName = eventModel.event; 364 | else if (eventModel.e_n) eventName = eventModel.e_n; 365 | 366 | eventModel.event_name = eventName; 367 | } 368 | 369 | return eventModel; 370 | } 371 | 372 | function exposeFPIDCookie(eventModel) { 373 | if (data.exposeFPIDCookie) { 374 | let fpid = getCookieValues('FPID'); 375 | 376 | if (fpid.length) { 377 | setCookie('FPIDP', fpid[0], { 378 | domain: 'auto', 379 | path: '/', 380 | samesite: getCookieType(eventModel), 381 | secure: true, 382 | 'max-age': 63072000, // 2 years 383 | httpOnly: false 384 | }); 385 | } 386 | } 387 | } 388 | 389 | function storeClientId(eventModel) { 390 | if (data.generateClientId) { 391 | setCookie('_dcid', eventModel.client_id, { 392 | domain: 'auto', 393 | path: '/', 394 | samesite: getCookieType(eventModel), 395 | secure: true, 396 | 'max-age': 63072000, // 2 years 397 | httpOnly: data.httpOnlyCookie || false 398 | }); 399 | } 400 | } 401 | 402 | function setCommonResponseHeaders(statusCode) { 403 | setResponseHeader('Access-Control-Max-Age', '600'); 404 | setResponseHeader('Access-Control-Allow-Origin', getRequestHeader('origin')); 405 | setResponseHeader( 406 | 'Access-Control-Allow-Methods', 407 | 'GET,POST,PUT,DELETE,OPTIONS' 408 | ); 409 | setResponseHeader( 410 | 'Access-Control-Allow-Headers', 411 | 'content-type,set-cookie,x-robots-tag,x-gtm-server-preview,x-stape-preview,x-stape-app-version' 412 | ); 413 | setResponseHeader('Access-Control-Allow-Credentials', 'true'); 414 | setResponseStatus(statusCode); 415 | } 416 | 417 | function getCookieType(eventModel) { 418 | if (!eventModel.page_location) { 419 | return 'Lax'; 420 | } 421 | 422 | const host = getRequestHeader('host'); 423 | const effectiveTldPlusOne = computeEffectiveTldPlusOne( 424 | eventModel.page_location 425 | ); 426 | 427 | if (!host || !effectiveTldPlusOne) { 428 | return 'Lax'; 429 | } 430 | 431 | if (host && host.indexOf(effectiveTldPlusOne) !== -1) { 432 | return 'Lax'; 433 | } 434 | 435 | return 'None'; 436 | } 437 | 438 | function prepareResponseBody(eventModels) { 439 | if (data.responseBody === 'empty') { 440 | return; 441 | } 442 | 443 | const responseModel = isEventModelsWrappedInArray 444 | ? eventModels[0] 445 | : eventModels; 446 | 447 | setResponseHeader('Content-Type', 'application/json'); 448 | 449 | if (data.responseBody === 'eventData') { 450 | setResponseBody(JSON.stringify(responseModel)); 451 | 452 | return; 453 | } 454 | 455 | if (isEventModelsWrappedInArray) { 456 | setResponseBody( 457 | JSON.stringify({ 458 | timestamp: responseModel.timestamp, 459 | unique_event_id: responseModel.unique_event_id 460 | }) 461 | ); 462 | return; 463 | } 464 | 465 | setResponseBody( 466 | JSON.stringify( 467 | eventModels.map((eventModel) => { 468 | return { 469 | timestamp: eventModel.timestamp, 470 | unique_event_id: eventModel.unique_event_id 471 | }; 472 | }) 473 | ) 474 | ); 475 | } 476 | 477 | function getEcommerceAction(eventModel) { 478 | if (eventModel.ecommerce) { 479 | const actions = [ 480 | 'detail', 481 | 'click', 482 | 'add', 483 | 'remove', 484 | 'checkout', 485 | 'checkout_option', 486 | 'purchase', 487 | 'refund' 488 | ]; 489 | 490 | for (let index = 0; index < actions.length; ++index) { 491 | const action = actions[index]; 492 | 493 | if (eventModel.ecommerce[action]) { 494 | return action; 495 | } 496 | } 497 | } 498 | 499 | return null; 500 | } 501 | 502 | function setRedirectLocation() { 503 | let location = data.redirectTo; 504 | if (data.lookupForRedirectToParam && data.redirectToQueryParamName) { 505 | const param = getRequestQueryParameter(data.redirectToQueryParamName); 506 | if (param && param.startsWith('http')) { 507 | location = param; 508 | } 509 | } 510 | setResponseHeader('location', location); 511 | } 512 | 513 | function setClientErrorResponseMessage() { 514 | if (data.clientErrorResponseMessage) { 515 | setResponseBody(data.clientErrorResponseMessage); 516 | } 517 | } 518 | 519 | function getEventModels(baseEventModel) { 520 | const body = getRequestBody(); 521 | 522 | if (body) { 523 | const contentType = getRequestHeader('content-type'); 524 | const isFormUrlEncoded = 525 | !!contentType && 526 | contentType.indexOf('application/x-www-form-urlencoded') !== -1; 527 | let bodyJson = isFormUrlEncoded ? parseUrlEncoded(body) : JSON.parse(body); 528 | if (bodyJson) { 529 | const bodyType = getType(bodyJson); 530 | const shouldUseOriginalBody = 531 | data.acceptMultipleEvents && bodyType === 'array'; 532 | if (!shouldUseOriginalBody) { 533 | bodyJson = [bodyJson]; 534 | isEventModelsWrappedInArray = true; 535 | } 536 | 537 | return bodyJson.map((bodyItem) => { 538 | const eventModel = assign( 539 | { 540 | timestamp: makeInteger(getTimestampMillis() / 1000), 541 | unique_event_id: 542 | getTimestampMillis() + '_' + generateRandom(100000000, 999999999) 543 | }, 544 | baseEventModel 545 | ); 546 | for (let bodyItemKey in bodyItem) { 547 | eventModel[bodyItemKey] = bodyItem[bodyItemKey]; 548 | } 549 | return eventModel; 550 | }); 551 | } 552 | } 553 | 554 | return [ 555 | assign( 556 | { 557 | timestamp: makeInteger(getTimestampMillis() / 1000), 558 | unique_event_id: 559 | getTimestampMillis() + '_' + generateRandom(100000000, 999999999) 560 | }, 561 | baseEventModel 562 | ) 563 | ]; 564 | } 565 | 566 | function getClientId(eventModels) { 567 | for (let i = 0; i < eventModels.length; i++) { 568 | const eventModel = eventModels[i]; 569 | const clientId = 570 | eventModel.client_id || eventModel.data_client_id || eventModel._dcid; 571 | if (clientId) return clientId; 572 | } 573 | 574 | const dcid = getCookieValues('_dcid'); 575 | if (dcid && dcid[0]) return dcid[0]; 576 | 577 | if (data.generateClientId) { 578 | for (let i = 0; i < eventModels.length; i++) { 579 | const eventModel = eventModels[i]; 580 | const tempClientId = eventModel._dcid_temp; 581 | if (tempClientId) return tempClientId; 582 | } 583 | 584 | return ( 585 | 'dcid.1.' + 586 | getTimestampMillis() + 587 | '.' + 588 | generateRandom(100000000, 999999999) 589 | ); 590 | } 591 | 592 | return ''; 593 | } 594 | 595 | /*============================================================================== 596 | Helpers 597 | ==============================================================================*/ 598 | 599 | function getObjectLength(object) { 600 | let length = 0; 601 | 602 | for (let key in object) { 603 | if (object.hasOwnProperty(key)) { 604 | ++length; 605 | } 606 | } 607 | return length; 608 | } 609 | 610 | function assign() { 611 | const target = arguments[0]; 612 | for (let i = 1; i < arguments.length; i++) { 613 | for (let key in arguments[i]) { 614 | target[key] = arguments[i][key]; 615 | } 616 | } 617 | return target; 618 | } 619 | 620 | function parseUrlEncoded(data) { 621 | const pairs = data.split('&'); 622 | const parsedData = {}; 623 | const regex = createRegex('\\+', 'g'); 624 | for (const pair of pairs) { 625 | const pairValue = pair.split('='); 626 | const key = pairValue[0]; 627 | const value = pairValue[1]; 628 | const keys = key 629 | .split('.') 630 | .map((k) => decodeUriComponent(k.replace(regex, ' '))); 631 | 632 | let currentObject = parsedData; 633 | 634 | for (let i = 0; i < keys.length - 1; i++) { 635 | const currentKey = keys[i]; 636 | 637 | if (!currentObject[currentKey]) { 638 | const nextKey = keys[i + 1]; 639 | const nextKeyIsNumber = makeString(makeInteger(nextKey)) === nextKey; 640 | currentObject[currentKey] = nextKeyIsNumber ? [] : {}; 641 | } 642 | 643 | currentObject = currentObject[currentKey]; 644 | } 645 | 646 | const lastKey = keys[keys.length - 1]; 647 | const decodedValue = decodeUriComponent(value.replace(regex, ' ')); 648 | const parsedValue = JSON.parse(decodedValue) || decodedValue; 649 | 650 | if (getType(currentObject) === 'array') { 651 | currentObject.push(parsedValue); 652 | } else { 653 | currentObject[lastKey] = parsedValue; 654 | } 655 | } 656 | 657 | return parsedData; 658 | } 659 | -------------------------------------------------------------------------------- /template.tpl: -------------------------------------------------------------------------------- 1 | ___TERMS_OF_SERVICE___ 2 | 3 | By creating or modifying this file you agree to Google Tag Manager's Community 4 | Template Gallery Developer Terms of Service available at 5 | https://developers.google.com/tag-manager/gallery-tos (or such other URL as 6 | Google may provide), as modified from time to time. 7 | 8 | 9 | ___INFO___ 10 | 11 | { 12 | "type": "CLIENT", 13 | "id": "cvt_temp_public_id", 14 | "version": 1, 15 | "securityGroups": [], 16 | "displayName": "Data Client", 17 | "brand": { 18 | "id": "brand_dummy", 19 | "displayName": "Stape", 20 | "thumbnail": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAAACXBI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gAIJAABQIAEAAAokAABAgQQAACiQAAAABRIAAKBAAgAAFEgAAIACCQAAUCABAAAKJAAAQIEEAAAokAAAAAUSAACgQAIAABRIAACAAgkAAFAgAQAACiQAAECBBAAAKNC/ART6p2FCXVSCAAAAAElFTkSuQmCC" 21 | }, 22 | "description": "Use this Client as a mapper from Request Data to Event Data.", 23 | "containerContexts": [ 24 | "SERVER" 25 | ] 26 | } 27 | 28 | 29 | ___TEMPLATE_PARAMETERS___ 30 | 31 | [ 32 | { 33 | "type": "CHECKBOX", 34 | "name": "exposeFPIDCookie", 35 | "checkboxText": "Expose FPID Cookie", 36 | "simpleValueType": true, 37 | "help": "If enabled, the FPID cookie only accessible by the server and generated by the GA4 Client, will be duplicated to FPIDP cookie, which will be accessible from in the browser by JavaScript. \n\u003cbr/\u003e\nIt\u0027s highly recommend using this option only in case it is necessary." 38 | }, 39 | { 40 | "type": "CHECKBOX", 41 | "name": "httpOnlyCookie", 42 | "checkboxText": "Write the _dcid cookie as HttpOnly", 43 | "simpleValueType": true, 44 | "help": "If enabled, the _dcid cookie will be written with the HttpOnly flag, making it non-accessible in the browser by JavaScript.", 45 | "defaultValue": false 46 | }, 47 | { 48 | "type": "CHECKBOX", 49 | "name": "generateClientId", 50 | "checkboxText": "Always generate client_id parameter", 51 | "simpleValueType": true, 52 | "help": "If enabled, even if the `client_id` parameter is not determined from the request, it will still be generated. The `client_id` parameter is required by GA4 tags.", 53 | "defaultValue": true 54 | }, 55 | { 56 | "type": "CHECKBOX", 57 | "name": "prolongCookies", 58 | "checkboxText": "Automatically prolong Data Tag cookies", 59 | "simpleValueType": true, 60 | "help": "If enabled, cookies generated by Data Tag will be reset from the server with an expiration time of 2 years. Its\u0027 useful if you use Data Tag store functionality.", 61 | "defaultValue": true 62 | }, 63 | { 64 | "type": "CHECKBOX", 65 | "name": "acceptMultipleEvents", 66 | "checkboxText": "Accept Multiple Events", 67 | "simpleValueType": true, 68 | "help": "When the Accept Multiple Events is set to true, the Data Client will parse an array of objects, in the request body, as separate events.\n\u003cbr/\u003e\nExample:\n\u003cbr/\u003e\n[\n {\"event\":\"page_view\"},\n {\"event\":\"view_item\"}\n]", 69 | "defaultValue": false 70 | }, 71 | { 72 | "type": "GROUP", 73 | "name": "responseSettings", 74 | "displayName": "Response Settings", 75 | "groupStyle": "ZIPPY_CLOSED", 76 | "subParams": [ 77 | { 78 | "type": "SELECT", 79 | "name": "responseStatusCode", 80 | "displayName": "Response Status Code", 81 | "selectItems": [ 82 | { 83 | "value": 200, 84 | "displayValue": "200" 85 | }, 86 | { 87 | "value": 201, 88 | "displayValue": "201" 89 | }, 90 | { 91 | "value": 301, 92 | "displayValue": "301" 93 | }, 94 | { 95 | "value": 302, 96 | "displayValue": "302" 97 | }, 98 | { 99 | "value": 403, 100 | "displayValue": "403" 101 | }, 102 | { 103 | "value": 404, 104 | "displayValue": "404" 105 | } 106 | ], 107 | "simpleValueType": true, 108 | "defaultValue": 200 109 | }, 110 | { 111 | "type": "GROUP", 112 | "name": "regularResponseSettings", 113 | "groupStyle": "NO_ZIPPY", 114 | "subParams": [ 115 | { 116 | "type": "SELECT", 117 | "name": "responseBody", 118 | "displayName": "Response Body", 119 | "macrosInSelect": false, 120 | "selectItems": [ 121 | { 122 | "value": "timestamp", 123 | "displayValue": "JSON Object with timestamp (recommended)" 124 | }, 125 | { 126 | "value": "eventData", 127 | "displayValue": "JSON Object with Event Data" 128 | }, 129 | { 130 | "value": "empty", 131 | "displayValue": "Empty" 132 | } 133 | ], 134 | "simpleValueType": true, 135 | "defaultValue": "timestamp" 136 | }, 137 | { 138 | "type": "CHECKBOX", 139 | "name": "responseBodyGet", 140 | "checkboxText": "Send Response Body for GET request", 141 | "simpleValueType": true, 142 | "help": "By default, for the GET request type, the answer is image pixel. \u003ca target\u003d\"_blank\" href\u003d\"https://developers.google.com/tag-manager/serverside/api#setpixelresponse\"\u003eMore Info\u003c/a\u003e." 143 | } 144 | ], 145 | "enablingConditions": [ 146 | { 147 | "paramName": "responseStatusCode", 148 | "paramValue": 200, 149 | "type": "EQUALS" 150 | }, 151 | { 152 | "paramName": "responseStatusCode", 153 | "paramValue": 201, 154 | "type": "EQUALS" 155 | } 156 | ] 157 | }, 158 | { 159 | "type": "GROUP", 160 | "name": "redirectResponseSettings", 161 | "groupStyle": "NO_ZIPPY", 162 | "subParams": [ 163 | { 164 | "type": "TEXT", 165 | "name": "redirectTo", 166 | "displayName": "Redirect To", 167 | "simpleValueType": true, 168 | "valueValidators": [ 169 | { 170 | "type": "NON_EMPTY" 171 | }, 172 | { 173 | "type": "REGEX", 174 | "args": [ 175 | "^https?:\\/\\/.*" 176 | ] 177 | } 178 | ] 179 | }, 180 | { 181 | "type": "CHECKBOX", 182 | "name": "lookupForRedirectToParam", 183 | "checkboxText": "Try to find redirect destination in query params", 184 | "simpleValueType": true, 185 | "help": "Override destination URL with query param from request url" 186 | }, 187 | { 188 | "type": "TEXT", 189 | "name": "redirectToQueryParamName", 190 | "displayName": "Query Param Name", 191 | "simpleValueType": true, 192 | "enablingConditions": [ 193 | { 194 | "paramName": "lookupForRedirectToParam", 195 | "paramValue": true, 196 | "type": "EQUALS" 197 | } 198 | ], 199 | "valueValidators": [ 200 | { 201 | "type": "NON_EMPTY" 202 | } 203 | ] 204 | } 205 | ], 206 | "enablingConditions": [ 207 | { 208 | "paramName": "responseStatusCode", 209 | "paramValue": 301, 210 | "type": "EQUALS" 211 | }, 212 | { 213 | "paramName": "responseStatusCode", 214 | "paramValue": 302, 215 | "type": "EQUALS" 216 | } 217 | ] 218 | }, 219 | { 220 | "type": "GROUP", 221 | "name": "clientErrorResponseSettings", 222 | "groupStyle": "NO_ZIPPY", 223 | "subParams": [ 224 | { 225 | "type": "TEXT", 226 | "name": "clientErrorResponseMessage", 227 | "displayName": "Client Error Response Message", 228 | "simpleValueType": true, 229 | "valueValidators": [ 230 | { 231 | "type": "NON_EMPTY" 232 | } 233 | ] 234 | } 235 | ], 236 | "enablingConditions": [ 237 | { 238 | "paramName": "responseStatusCode", 239 | "paramValue": 403, 240 | "type": "EQUALS" 241 | }, 242 | { 243 | "paramName": "responseStatusCode", 244 | "paramValue": 404, 245 | "type": "EQUALS" 246 | } 247 | ] 248 | } 249 | ] 250 | }, 251 | { 252 | "type": "GROUP", 253 | "name": "pathSettings", 254 | "displayName": "Accepted Path Settings", 255 | "groupStyle": "ZIPPY_CLOSED", 256 | "subParams": [ 257 | { 258 | "type": "SIMPLE_TABLE", 259 | "name": "path", 260 | "displayName": "Type additional paths that will be claimed by this client", 261 | "simpleTableColumns": [ 262 | { 263 | "defaultValue": "", 264 | "displayName": "For example: /callback", 265 | "name": "path", 266 | "type": "TEXT", 267 | "isUnique": true, 268 | "valueValidators": [ 269 | { 270 | "type": "NON_EMPTY" 271 | } 272 | ] 273 | } 274 | ], 275 | "newRowButtonText": "Add path", 276 | "help": "By default path \u003cb\u003e/data\u003c/b\u003e will be claimed. But you can add more paths that will be claimed by this client." 277 | } 278 | ] 279 | } 280 | ] 281 | 282 | 283 | ___SANDBOXED_JS_FOR_SERVER___ 284 | 285 | const returnResponse = require('returnResponse'); 286 | const runContainer = require('runContainer'); 287 | const setResponseHeader = require('setResponseHeader'); 288 | const setResponseStatus = require('setResponseStatus'); 289 | const setResponseBody = require('setResponseBody'); 290 | const JSON = require('JSON'); 291 | const fromBase64 = require('fromBase64'); 292 | const getTimestampMillis = require('getTimestampMillis'); 293 | const getCookieValues = require('getCookieValues'); 294 | const getRequestBody = require('getRequestBody'); 295 | const getRequestMethod = require('getRequestMethod'); 296 | const getRequestHeader = require('getRequestHeader'); 297 | const getRequestPath = require('getRequestPath'); 298 | const getRequestQueryParameters = require('getRequestQueryParameters'); 299 | const makeInteger = require('makeInteger'); 300 | const getRemoteAddress = require('getRemoteAddress'); 301 | const setCookie = require('setCookie'); 302 | const setPixelResponse = require('setPixelResponse'); 303 | const generateRandom = require('generateRandom'); 304 | const computeEffectiveTldPlusOne = require('computeEffectiveTldPlusOne'); 305 | const getRequestQueryParameter = require('getRequestQueryParameter'); 306 | const getType = require('getType'); 307 | const decodeUriComponent = require('decodeUriComponent'); 308 | const createRegex = require('createRegex'); 309 | const makeString = require('makeString'); 310 | const Object = require('Object'); 311 | 312 | /*============================================================================== 313 | ==============================================================================*/ 314 | 315 | const requestMethod = getRequestMethod(); 316 | const path = getRequestPath(); 317 | let isClientUsed = false; 318 | let isEventModelsWrappedInArray = false; 319 | 320 | if (path === '/data') { 321 | runClient(); 322 | } 323 | 324 | if (data.path && !isClientUsed) { 325 | for (let key in data.path) { 326 | if (!isClientUsed && data.path[key].path === path) { 327 | runClient(); 328 | } 329 | } 330 | } 331 | 332 | /*============================================================================== 333 | Vendor related functions 334 | ==============================================================================*/ 335 | 336 | function runClient() { 337 | isClientUsed = true; 338 | require('claimRequest')(); 339 | 340 | if (requestMethod === 'OPTIONS') { 341 | setCommonResponseHeaders(200); 342 | returnResponse(); 343 | return; 344 | } 345 | const baseEventModel = getBaseEventModelWithQueryParameters(); 346 | let eventModels = getEventModels(baseEventModel); 347 | const clientId = getClientId(eventModels); 348 | eventModels = eventModels.map((eventModel) => { 349 | eventModel = addRequiredParametersToEventModel(eventModel); 350 | eventModel = addCommonParametersToEventModel(eventModel); 351 | eventModel = addClientIdToEventModel(eventModel, clientId); 352 | if (eventModel._dcid_temp) Object.delete(eventModel, '_dcid_temp'); 353 | return eventModel; 354 | }); 355 | 356 | storeClientId(eventModels[0]); 357 | exposeFPIDCookie(eventModels[0]); 358 | prolongDataTagCookies(eventModels[0]); 359 | const responseStatusCode = makeInteger(data.responseStatusCode || 200); 360 | setCommonResponseHeaders(responseStatusCode); 361 | 362 | let counter = 0; 363 | eventModels.forEach((event) => { 364 | runContainer(event, () => { 365 | if (++counter === eventModels.length) { 366 | switch (responseStatusCode) { 367 | case 200: 368 | case 201: 369 | if (requestMethod === 'POST' || data.responseBodyGet) { 370 | prepareResponseBody(eventModels); 371 | } else { 372 | setPixelResponse(); 373 | } 374 | break; 375 | case 301: 376 | case 302: 377 | setRedirectLocation(); 378 | break; 379 | case 403: 380 | case 404: 381 | setClientErrorResponseMessage(); 382 | break; 383 | } 384 | 385 | returnResponse(); 386 | } 387 | }); 388 | }); 389 | } 390 | 391 | function addCommonParametersToEventModel(eventModel) { 392 | if (!eventModel.ip_override) { 393 | if (eventModel.ip) eventModel.ip_override = eventModel.ip; 394 | else if (eventModel.ipOverride) 395 | eventModel.ip_override = eventModel.ipOverride; 396 | else eventModel.ip_override = getRemoteAddress(); 397 | } 398 | 399 | if (!eventModel.user_agent) { 400 | if (eventModel.userAgent) eventModel.user_agent = eventModel.userAgent; 401 | else if (getRequestHeader('User-Agent')) 402 | eventModel.user_agent = getRequestHeader('User-Agent'); 403 | } 404 | 405 | if (!eventModel.language) { 406 | const acceptLanguageHeader = getRequestHeader('Accept-Language'); 407 | 408 | if (acceptLanguageHeader) { 409 | eventModel.language = acceptLanguageHeader 410 | .split(';')[0] 411 | .substring(0, 2) 412 | .toLowerCase(); 413 | } 414 | } 415 | 416 | if (!eventModel.page_hostname) { 417 | if (eventModel.pageHostname) 418 | eventModel.page_hostname = eventModel.pageHostname; 419 | else if (eventModel.hostname) 420 | eventModel.page_hostname = eventModel.hostname; 421 | } 422 | 423 | if (!eventModel.page_location) { 424 | if (eventModel.pageLocation) 425 | eventModel.page_location = eventModel.pageLocation; 426 | else if (eventModel.url) eventModel.page_location = eventModel.url; 427 | else if (eventModel.href) eventModel.page_location = eventModel.href; 428 | } 429 | 430 | if (!eventModel.page_referrer) { 431 | if (eventModel.pageReferrer) 432 | eventModel.page_referrer = eventModel.pageReferrer; 433 | else if (eventModel.referrer) 434 | eventModel.page_referrer = eventModel.referrer; 435 | else if (eventModel.urlref) eventModel.page_referrer = eventModel.urlref; 436 | } 437 | 438 | if (!eventModel.value && eventModel.e_v) eventModel.value = eventModel.e_v; 439 | 440 | if (getType(eventModel.items) === 'array' && eventModel.items.length) { 441 | const firstItem = eventModel.items[0]; 442 | if (!eventModel.currency && firstItem.currency) 443 | eventModel.currency = firstItem.currency; 444 | if (eventModel.items.length === 1) { 445 | if (!eventModel.item_id && firstItem.item_id) 446 | eventModel.item_id = firstItem.item_id; 447 | if (!eventModel.item_name && firstItem.item_name) 448 | eventModel.item_name = firstItem.item_name; 449 | if (!eventModel.item_brand && firstItem.item_brand) 450 | eventModel.item_brand = firstItem.item_brand; 451 | if (!eventModel.item_quantity && firstItem.quantity) 452 | eventModel.item_quantity = firstItem.quantity; 453 | if (!eventModel.item_category && firstItem.item_category) 454 | eventModel.item_category = firstItem.item_category; 455 | if (!eventModel.item_price && firstItem.price) 456 | eventModel.item_price = firstItem.price; 457 | } 458 | if (!eventModel.value) { 459 | const valueFromItems = eventModel.items.reduce((acc, item) => { 460 | if (!item.price) return acc; 461 | const quantity = item.quantity ? item.quantity : 1; 462 | return acc + quantity * item.price; 463 | }, 0); 464 | if (valueFromItems) eventModel.value = valueFromItems; 465 | } 466 | } 467 | 468 | const ecommerceAction = getEcommerceAction(eventModel); 469 | 470 | if (ecommerceAction) { 471 | if (!eventModel['x-ga-mp1-pa']) eventModel['x-ga-mp1-pa'] = ecommerceAction; 472 | 473 | if ( 474 | ecommerceAction === 'purchase' && 475 | eventModel.ecommerce.purchase.actionField 476 | ) { 477 | if (!eventModel['x-ga-mp1-tr']) 478 | eventModel['x-ga-mp1-tr'] = 479 | eventModel.ecommerce.purchase.actionField.revenue; 480 | if (!eventModel.revenue) 481 | eventModel.revenue = eventModel.ecommerce.purchase.actionField.revenue; 482 | if (!eventModel.affiliation) 483 | eventModel.affiliation = 484 | eventModel.ecommerce.purchase.actionField.affiliation; 485 | if (!eventModel.tax) 486 | eventModel.tax = eventModel.ecommerce.purchase.actionField.tax; 487 | if (!eventModel.shipping) 488 | eventModel.shipping = 489 | eventModel.ecommerce.purchase.actionField.shipping; 490 | if (!eventModel.coupon) 491 | eventModel.coupon = eventModel.ecommerce.purchase.actionField.coupon; 492 | if (!eventModel.transaction_id) 493 | eventModel.transaction_id = 494 | eventModel.ecommerce.purchase.actionField.id; 495 | } 496 | } 497 | 498 | if (!eventModel.page_encoding && eventModel.pageEncoding) 499 | eventModel.page_encoding = eventModel.pageEncoding; 500 | if (!eventModel.page_path && eventModel.pagePath) 501 | eventModel.page_path = eventModel.pagePath; 502 | if (!eventModel.page_title && eventModel.pageTitle) 503 | eventModel.page_title = eventModel.pageTitle; 504 | if (!eventModel.screen_resolution && eventModel.screenResolution) 505 | eventModel.screen_resolution = eventModel.screenResolution; 506 | if (!eventModel.viewport_size && eventModel.viewportSize) 507 | eventModel.viewport_size = eventModel.viewportSize; 508 | if (!eventModel.user_id && eventModel.userId) 509 | eventModel.user_id = eventModel.userId; 510 | 511 | if (!eventModel.user_data) { 512 | let userData = {}; 513 | let userAddressData = {}; 514 | 515 | if (!userData.email_address) { 516 | if (eventModel.userEmail) userData.email_address = eventModel.userEmail; 517 | else if (eventModel.email_address) 518 | userData.email_address = eventModel.email_address; 519 | else if (eventModel.email) userData.email_address = eventModel.email; 520 | else if (eventModel.mail) userData.email_address = eventModel.mail; 521 | } 522 | 523 | if (!userData.phone_number) { 524 | if (eventModel.userPhoneNumber) 525 | userData.phone_number = eventModel.userPhoneNumber; 526 | else if (eventModel.phone_number) 527 | userData.phone_number = eventModel.phone_number; 528 | else if (eventModel.phoneNumber) 529 | userData.phone_number = eventModel.phoneNumber; 530 | else if (eventModel.phone) userData.phone_number = eventModel.phone; 531 | } 532 | 533 | if (!userAddressData.street && eventModel.street) 534 | userAddressData.street = eventModel.street; 535 | if (!userAddressData.city && eventModel.city) 536 | userAddressData.city = eventModel.city; 537 | if (!userAddressData.region && eventModel.region) 538 | userAddressData.region = eventModel.region; 539 | if (!userAddressData.country && eventModel.country) 540 | userAddressData.country = eventModel.country; 541 | 542 | if (!userAddressData.first_name) { 543 | if (eventModel.userFirstName) 544 | userAddressData.first_name = eventModel.userFirstName; 545 | else if (eventModel.first_name) 546 | userAddressData.first_name = eventModel.first_name; 547 | else if (eventModel.firstName) 548 | userAddressData.first_name = eventModel.firstName; 549 | else if (eventModel.name) userAddressData.first_name = eventModel.name; 550 | } 551 | 552 | if (!userAddressData.last_name) { 553 | if (eventModel.userLastName) 554 | userAddressData.last_name = eventModel.userLastName; 555 | else if (eventModel.last_name) 556 | userAddressData.last_name = eventModel.last_name; 557 | else if (eventModel.lastName) 558 | userAddressData.last_name = eventModel.lastName; 559 | else if (eventModel.surname) 560 | userAddressData.last_name = eventModel.surname; 561 | else if (eventModel.family_name) 562 | userAddressData.last_name = eventModel.family_name; 563 | else if (eventModel.familyName) 564 | userAddressData.last_name = eventModel.familyName; 565 | } 566 | 567 | if (!userAddressData.region) { 568 | if (eventModel.region) userAddressData.region = eventModel.region; 569 | else if (eventModel.state) userAddressData.region = eventModel.state; 570 | } 571 | 572 | if (!userAddressData.postal_code) { 573 | if (eventModel.postal_code) 574 | userAddressData.postal_code = eventModel.postal_code; 575 | else if (eventModel.postalCode) 576 | userAddressData.postal_code = eventModel.postalCode; 577 | else if (eventModel.zip) userAddressData.postal_code = eventModel.zip; 578 | } 579 | 580 | if (getObjectLength(userAddressData) !== 0) { 581 | userData.address = userAddressData; 582 | } 583 | 584 | if (!eventModel.user_data && getObjectLength(userData) !== 0) { 585 | eventModel.user_data = userData; 586 | } 587 | } 588 | 589 | return eventModel; 590 | } 591 | 592 | function getBaseEventModelWithQueryParameters() { 593 | const requestQueryParameters = getRequestQueryParameters(); 594 | const eventModel = {}; 595 | 596 | if (requestQueryParameters) { 597 | for (let queryParameterKey in requestQueryParameters) { 598 | if ( 599 | (queryParameterKey === 'dtcd' || queryParameterKey === 'dtdc') && 600 | requestMethod === 'GET' 601 | ) { 602 | let dt = 603 | queryParameterKey === 'dtcd' 604 | ? JSON.parse(requestQueryParameters[queryParameterKey]) 605 | : JSON.parse(fromBase64(requestQueryParameters[queryParameterKey])); 606 | 607 | for (let dtKey in dt) { 608 | eventModel[dtKey] = dt[dtKey]; 609 | } 610 | } else { 611 | eventModel[queryParameterKey] = 612 | requestQueryParameters[queryParameterKey]; 613 | } 614 | } 615 | } 616 | 617 | return eventModel; 618 | } 619 | 620 | function addClientIdToEventModel(eventModel, clientId) { 621 | eventModel.client_id = clientId; 622 | return eventModel; 623 | } 624 | 625 | function prolongDataTagCookies(eventModel) { 626 | if (data.prolongCookies) { 627 | let stapeData = getCookieValues('stape'); 628 | 629 | if (stapeData.length) { 630 | setCookie('stape', stapeData[0], { 631 | domain: 'auto', 632 | path: '/', 633 | samesite: getCookieType(eventModel), 634 | secure: true, 635 | 'max-age': 63072000, // 2 years 636 | httpOnly: false 637 | }); 638 | } 639 | } 640 | } 641 | 642 | function addRequiredParametersToEventModel(eventModel) { 643 | if (!eventModel.event_name) { 644 | let eventName = 'Data'; 645 | 646 | if (eventModel.eventName) eventName = eventModel.eventName; 647 | else if (eventModel.event) eventName = eventModel.event; 648 | else if (eventModel.e_n) eventName = eventModel.e_n; 649 | 650 | eventModel.event_name = eventName; 651 | } 652 | 653 | return eventModel; 654 | } 655 | 656 | function exposeFPIDCookie(eventModel) { 657 | if (data.exposeFPIDCookie) { 658 | let fpid = getCookieValues('FPID'); 659 | 660 | if (fpid.length) { 661 | setCookie('FPIDP', fpid[0], { 662 | domain: 'auto', 663 | path: '/', 664 | samesite: getCookieType(eventModel), 665 | secure: true, 666 | 'max-age': 63072000, // 2 years 667 | httpOnly: false 668 | }); 669 | } 670 | } 671 | } 672 | 673 | function storeClientId(eventModel) { 674 | if (data.generateClientId) { 675 | setCookie('_dcid', eventModel.client_id, { 676 | domain: 'auto', 677 | path: '/', 678 | samesite: getCookieType(eventModel), 679 | secure: true, 680 | 'max-age': 63072000, // 2 years 681 | httpOnly: data.httpOnlyCookie || false 682 | }); 683 | } 684 | } 685 | 686 | function setCommonResponseHeaders(statusCode) { 687 | setResponseHeader('Access-Control-Max-Age', '600'); 688 | setResponseHeader('Access-Control-Allow-Origin', getRequestHeader('origin')); 689 | setResponseHeader( 690 | 'Access-Control-Allow-Methods', 691 | 'GET,POST,PUT,DELETE,OPTIONS' 692 | ); 693 | setResponseHeader( 694 | 'Access-Control-Allow-Headers', 695 | 'content-type,set-cookie,x-robots-tag,x-gtm-server-preview,x-stape-preview,x-stape-app-version' 696 | ); 697 | setResponseHeader('Access-Control-Allow-Credentials', 'true'); 698 | setResponseStatus(statusCode); 699 | } 700 | 701 | function getCookieType(eventModel) { 702 | if (!eventModel.page_location) { 703 | return 'Lax'; 704 | } 705 | 706 | const host = getRequestHeader('host'); 707 | const effectiveTldPlusOne = computeEffectiveTldPlusOne( 708 | eventModel.page_location 709 | ); 710 | 711 | if (!host || !effectiveTldPlusOne) { 712 | return 'Lax'; 713 | } 714 | 715 | if (host && host.indexOf(effectiveTldPlusOne) !== -1) { 716 | return 'Lax'; 717 | } 718 | 719 | return 'None'; 720 | } 721 | 722 | function prepareResponseBody(eventModels) { 723 | if (data.responseBody === 'empty') { 724 | return; 725 | } 726 | 727 | const responseModel = isEventModelsWrappedInArray 728 | ? eventModels[0] 729 | : eventModels; 730 | 731 | setResponseHeader('Content-Type', 'application/json'); 732 | 733 | if (data.responseBody === 'eventData') { 734 | setResponseBody(JSON.stringify(responseModel)); 735 | 736 | return; 737 | } 738 | 739 | if (isEventModelsWrappedInArray) { 740 | setResponseBody( 741 | JSON.stringify({ 742 | timestamp: responseModel.timestamp, 743 | unique_event_id: responseModel.unique_event_id 744 | }) 745 | ); 746 | return; 747 | } 748 | 749 | setResponseBody( 750 | JSON.stringify( 751 | eventModels.map((eventModel) => { 752 | return { 753 | timestamp: eventModel.timestamp, 754 | unique_event_id: eventModel.unique_event_id 755 | }; 756 | }) 757 | ) 758 | ); 759 | } 760 | 761 | function getEcommerceAction(eventModel) { 762 | if (eventModel.ecommerce) { 763 | const actions = [ 764 | 'detail', 765 | 'click', 766 | 'add', 767 | 'remove', 768 | 'checkout', 769 | 'checkout_option', 770 | 'purchase', 771 | 'refund' 772 | ]; 773 | 774 | for (let index = 0; index < actions.length; ++index) { 775 | const action = actions[index]; 776 | 777 | if (eventModel.ecommerce[action]) { 778 | return action; 779 | } 780 | } 781 | } 782 | 783 | return null; 784 | } 785 | 786 | function setRedirectLocation() { 787 | let location = data.redirectTo; 788 | if (data.lookupForRedirectToParam && data.redirectToQueryParamName) { 789 | const param = getRequestQueryParameter(data.redirectToQueryParamName); 790 | if (param && param.startsWith('http')) { 791 | location = param; 792 | } 793 | } 794 | setResponseHeader('location', location); 795 | } 796 | 797 | function setClientErrorResponseMessage() { 798 | if (data.clientErrorResponseMessage) { 799 | setResponseBody(data.clientErrorResponseMessage); 800 | } 801 | } 802 | 803 | function getEventModels(baseEventModel) { 804 | const body = getRequestBody(); 805 | 806 | if (body) { 807 | const contentType = getRequestHeader('content-type'); 808 | const isFormUrlEncoded = 809 | !!contentType && 810 | contentType.indexOf('application/x-www-form-urlencoded') !== -1; 811 | let bodyJson = isFormUrlEncoded ? parseUrlEncoded(body) : JSON.parse(body); 812 | if (bodyJson) { 813 | const bodyType = getType(bodyJson); 814 | const shouldUseOriginalBody = 815 | data.acceptMultipleEvents && bodyType === 'array'; 816 | if (!shouldUseOriginalBody) { 817 | bodyJson = [bodyJson]; 818 | isEventModelsWrappedInArray = true; 819 | } 820 | 821 | return bodyJson.map((bodyItem) => { 822 | const eventModel = assign( 823 | { 824 | timestamp: makeInteger(getTimestampMillis() / 1000), 825 | unique_event_id: 826 | getTimestampMillis() + '_' + generateRandom(100000000, 999999999) 827 | }, 828 | baseEventModel 829 | ); 830 | for (let bodyItemKey in bodyItem) { 831 | eventModel[bodyItemKey] = bodyItem[bodyItemKey]; 832 | } 833 | return eventModel; 834 | }); 835 | } 836 | } 837 | 838 | return [ 839 | assign( 840 | { 841 | timestamp: makeInteger(getTimestampMillis() / 1000), 842 | unique_event_id: 843 | getTimestampMillis() + '_' + generateRandom(100000000, 999999999) 844 | }, 845 | baseEventModel 846 | ) 847 | ]; 848 | } 849 | 850 | function getClientId(eventModels) { 851 | for (let i = 0; i < eventModels.length; i++) { 852 | const eventModel = eventModels[i]; 853 | const clientId = 854 | eventModel.client_id || eventModel.data_client_id || eventModel._dcid; 855 | if (clientId) return clientId; 856 | } 857 | 858 | const dcid = getCookieValues('_dcid'); 859 | if (dcid && dcid[0]) return dcid[0]; 860 | 861 | if (data.generateClientId) { 862 | for (let i = 0; i < eventModels.length; i++) { 863 | const eventModel = eventModels[i]; 864 | const tempClientId = eventModel._dcid_temp; 865 | if (tempClientId) return tempClientId; 866 | } 867 | 868 | return ( 869 | 'dcid.1.' + 870 | getTimestampMillis() + 871 | '.' + 872 | generateRandom(100000000, 999999999) 873 | ); 874 | } 875 | 876 | return ''; 877 | } 878 | 879 | /*============================================================================== 880 | Helpers 881 | ==============================================================================*/ 882 | 883 | function getObjectLength(object) { 884 | let length = 0; 885 | 886 | for (let key in object) { 887 | if (object.hasOwnProperty(key)) { 888 | ++length; 889 | } 890 | } 891 | return length; 892 | } 893 | 894 | function assign() { 895 | const target = arguments[0]; 896 | for (let i = 1; i < arguments.length; i++) { 897 | for (let key in arguments[i]) { 898 | target[key] = arguments[i][key]; 899 | } 900 | } 901 | return target; 902 | } 903 | 904 | function parseUrlEncoded(data) { 905 | const pairs = data.split('&'); 906 | const parsedData = {}; 907 | const regex = createRegex('\\+', 'g'); 908 | for (const pair of pairs) { 909 | const pairValue = pair.split('='); 910 | const key = pairValue[0]; 911 | const value = pairValue[1]; 912 | const keys = key 913 | .split('.') 914 | .map((k) => decodeUriComponent(k.replace(regex, ' '))); 915 | 916 | let currentObject = parsedData; 917 | 918 | for (let i = 0; i < keys.length - 1; i++) { 919 | const currentKey = keys[i]; 920 | 921 | if (!currentObject[currentKey]) { 922 | const nextKey = keys[i + 1]; 923 | const nextKeyIsNumber = makeString(makeInteger(nextKey)) === nextKey; 924 | currentObject[currentKey] = nextKeyIsNumber ? [] : {}; 925 | } 926 | 927 | currentObject = currentObject[currentKey]; 928 | } 929 | 930 | const lastKey = keys[keys.length - 1]; 931 | const decodedValue = decodeUriComponent(value.replace(regex, ' ')); 932 | const parsedValue = JSON.parse(decodedValue) || decodedValue; 933 | 934 | if (getType(currentObject) === 'array') { 935 | currentObject.push(parsedValue); 936 | } else { 937 | currentObject[lastKey] = parsedValue; 938 | } 939 | } 940 | 941 | return parsedData; 942 | } 943 | 944 | 945 | ___SERVER_PERMISSIONS___ 946 | 947 | [ 948 | { 949 | "instance": { 950 | "key": { 951 | "publicId": "return_response", 952 | "versionId": "1" 953 | }, 954 | "param": [] 955 | }, 956 | "isRequired": true 957 | }, 958 | { 959 | "instance": { 960 | "key": { 961 | "publicId": "access_response", 962 | "versionId": "1" 963 | }, 964 | "param": [ 965 | { 966 | "key": "writeResponseAccess", 967 | "value": { 968 | "type": 1, 969 | "string": "any" 970 | } 971 | }, 972 | { 973 | "key": "writeHeaderAccess", 974 | "value": { 975 | "type": 1, 976 | "string": "specific" 977 | } 978 | } 979 | ] 980 | }, 981 | "clientAnnotations": { 982 | "isEditedByUser": true 983 | }, 984 | "isRequired": true 985 | }, 986 | { 987 | "instance": { 988 | "key": { 989 | "publicId": "run_container", 990 | "versionId": "1" 991 | }, 992 | "param": [] 993 | }, 994 | "isRequired": true 995 | }, 996 | { 997 | "instance": { 998 | "key": { 999 | "publicId": "get_cookies", 1000 | "versionId": "1" 1001 | }, 1002 | "param": [ 1003 | { 1004 | "key": "cookieAccess", 1005 | "value": { 1006 | "type": 1, 1007 | "string": "specific" 1008 | } 1009 | }, 1010 | { 1011 | "key": "cookieNames", 1012 | "value": { 1013 | "type": 2, 1014 | "listItem": [ 1015 | { 1016 | "type": 1, 1017 | "string": "stape" 1018 | }, 1019 | { 1020 | "type": 1, 1021 | "string": "_dcid" 1022 | }, 1023 | { 1024 | "type": 1, 1025 | "string": "FPIDP" 1026 | }, 1027 | { 1028 | "type": 1, 1029 | "string": "FPID" 1030 | } 1031 | ] 1032 | } 1033 | } 1034 | ] 1035 | }, 1036 | "clientAnnotations": { 1037 | "isEditedByUser": true 1038 | }, 1039 | "isRequired": true 1040 | }, 1041 | { 1042 | "instance": { 1043 | "key": { 1044 | "publicId": "read_request", 1045 | "versionId": "1" 1046 | }, 1047 | "param": [ 1048 | { 1049 | "key": "requestAccess", 1050 | "value": { 1051 | "type": 1, 1052 | "string": "any" 1053 | } 1054 | }, 1055 | { 1056 | "key": "headerAccess", 1057 | "value": { 1058 | "type": 1, 1059 | "string": "any" 1060 | } 1061 | }, 1062 | { 1063 | "key": "queryParameterAccess", 1064 | "value": { 1065 | "type": 1, 1066 | "string": "any" 1067 | } 1068 | } 1069 | ] 1070 | }, 1071 | "clientAnnotations": { 1072 | "isEditedByUser": true 1073 | }, 1074 | "isRequired": true 1075 | }, 1076 | { 1077 | "instance": { 1078 | "key": { 1079 | "publicId": "set_cookies", 1080 | "versionId": "1" 1081 | }, 1082 | "param": [ 1083 | { 1084 | "key": "allowedCookies", 1085 | "value": { 1086 | "type": 2, 1087 | "listItem": [ 1088 | { 1089 | "type": 3, 1090 | "mapKey": [ 1091 | { 1092 | "type": 1, 1093 | "string": "name" 1094 | }, 1095 | { 1096 | "type": 1, 1097 | "string": "domain" 1098 | }, 1099 | { 1100 | "type": 1, 1101 | "string": "path" 1102 | }, 1103 | { 1104 | "type": 1, 1105 | "string": "secure" 1106 | }, 1107 | { 1108 | "type": 1, 1109 | "string": "session" 1110 | } 1111 | ], 1112 | "mapValue": [ 1113 | { 1114 | "type": 1, 1115 | "string": "stape" 1116 | }, 1117 | { 1118 | "type": 1, 1119 | "string": "*" 1120 | }, 1121 | { 1122 | "type": 1, 1123 | "string": "*" 1124 | }, 1125 | { 1126 | "type": 1, 1127 | "string": "any" 1128 | }, 1129 | { 1130 | "type": 1, 1131 | "string": "any" 1132 | } 1133 | ] 1134 | }, 1135 | { 1136 | "type": 3, 1137 | "mapKey": [ 1138 | { 1139 | "type": 1, 1140 | "string": "name" 1141 | }, 1142 | { 1143 | "type": 1, 1144 | "string": "domain" 1145 | }, 1146 | { 1147 | "type": 1, 1148 | "string": "path" 1149 | }, 1150 | { 1151 | "type": 1, 1152 | "string": "secure" 1153 | }, 1154 | { 1155 | "type": 1, 1156 | "string": "session" 1157 | } 1158 | ], 1159 | "mapValue": [ 1160 | { 1161 | "type": 1, 1162 | "string": "_dcid" 1163 | }, 1164 | { 1165 | "type": 1, 1166 | "string": "*" 1167 | }, 1168 | { 1169 | "type": 1, 1170 | "string": "*" 1171 | }, 1172 | { 1173 | "type": 1, 1174 | "string": "any" 1175 | }, 1176 | { 1177 | "type": 1, 1178 | "string": "any" 1179 | } 1180 | ] 1181 | }, 1182 | { 1183 | "type": 3, 1184 | "mapKey": [ 1185 | { 1186 | "type": 1, 1187 | "string": "name" 1188 | }, 1189 | { 1190 | "type": 1, 1191 | "string": "domain" 1192 | }, 1193 | { 1194 | "type": 1, 1195 | "string": "path" 1196 | }, 1197 | { 1198 | "type": 1, 1199 | "string": "secure" 1200 | }, 1201 | { 1202 | "type": 1, 1203 | "string": "session" 1204 | } 1205 | ], 1206 | "mapValue": [ 1207 | { 1208 | "type": 1, 1209 | "string": "FPIDP" 1210 | }, 1211 | { 1212 | "type": 1, 1213 | "string": "*" 1214 | }, 1215 | { 1216 | "type": 1, 1217 | "string": "*" 1218 | }, 1219 | { 1220 | "type": 1, 1221 | "string": "any" 1222 | }, 1223 | { 1224 | "type": 1, 1225 | "string": "any" 1226 | } 1227 | ] 1228 | } 1229 | ] 1230 | } 1231 | } 1232 | ] 1233 | }, 1234 | "clientAnnotations": { 1235 | "isEditedByUser": true 1236 | }, 1237 | "isRequired": true 1238 | } 1239 | ] 1240 | 1241 | 1242 | ___TESTS___ 1243 | 1244 | scenarios: 1245 | - name: runContainer is called succesfully for a single event and response is sent 1246 | back once 1247 | code: "mock('getRequestPath', '/data');\nmock('requestMethod', 'POST');\nmock('getRequestBody',\ 1248 | \ '{\"event\":\"page_view\",\"client_id\":\"client_id\"}');\n\n/* \n For some\ 1249 | \ reason when we use \"assertApi('claimRequest').wasCalled()\" AND we run all\ 1250 | \ the tests,\n it produces the following error \"Tried to claim a request after\ 1251 | \ a Client had returned. Calling claimRequest from a callback is not supported.\"\ 1252 | \n If we run only this single test, the error does not occur.\n A workaround\ 1253 | \ is to mock 'claimRequest' API and make a dummy assertion in the mocked function.\ 1254 | \ This way we make sure it's been called.\n*/\nlet claimRequestWasCalled;\nmock('claimRequest',\ 1255 | \ () => {\n claimRequestWasCalled = true;\n});\n\nlet runContainerExecutions\ 1256 | \ = 0;\nconst runContainerExpectedExecutions = 1;\nmock('runContainer', (eventData,\ 1257 | \ onCompleteCallback, onStartCallback) => {\n assertThat(eventData).isObject();\n\ 1258 | \ runContainerExecutions++;\n assertThat(onCompleteCallback).isFunction();\n\ 1259 | \ onCompleteCallback();\n});\n\nmock('returnResponse', () => {\n if (runContainerExecutions\ 1260 | \ !== runContainerExpectedExecutions) {\n fail('returnResponse should be called\ 1261 | \ by the last runContainer onComplete callback execution only.');\n return;\n\ 1262 | \ }\n assertThat(true).isTrue(); // Dummy to cover the case when runContainerExecutions\ 1263 | \ === runContainerExpectedExecutions.\n});\n\nrunCode(mockData);\n\ncallLater(()\ 1264 | \ => {\n assertThat(claimRequestWasCalled).isTrue();\n assertApi('setResponseStatus').wasCalledWith(200);\n\ 1265 | \ assertThat(runContainerExecutions).isEqualTo(runContainerExpectedExecutions);\n\ 1266 | });" 1267 | - name: runContainer is called succesfully for multiple events and response is sent 1268 | back once 1269 | code: "mockData.acceptMultipleEvents = true;\n\nmock('getRequestPath', '/data');\n\ 1270 | mock('requestMethod', 'POST');\nmock('getRequestBody', '[{\"event\":\"page_view\"\ 1271 | ,\"client_id\":\"client_id\"},{\"event\":\"view_item\",\"client_id\":\"client_id\"\ 1272 | }]');\n\n/* \n For some reason when we use \"assertApi('claimRequest').wasCalled()\"\ 1273 | \ AND we run all the tests,\n it produces the following error \"Tried to claim\ 1274 | \ a request after a Client had returned. Calling claimRequest from a callback\ 1275 | \ is not supported.\"\n If we run only this single test, the error does not occur.\n\ 1276 | \ A workaround is to mock 'claimRequest' API and make a dummy assertion in the\ 1277 | \ mocked function. This way we make sure it's been called.\n*/\nlet claimRequestWasCalled;\n\ 1278 | mock('claimRequest', () => {\n claimRequestWasCalled = true;\n});\n\nlet runContainerExecutions\ 1279 | \ = 0;\nconst runContainerExpectedExecutions = 2;\nmock('runContainer', (eventData,\ 1280 | \ onCompleteCallback, onStartCallback) => {\n assertThat(eventData).isObject();\n\ 1281 | \ runContainerExecutions++;\n assertThat(onCompleteCallback).isFunction();\n\ 1282 | \ onCompleteCallback();\n});\n\nmock('returnResponse', () => {\n if (runContainerExecutions\ 1283 | \ !== runContainerExpectedExecutions) {\n fail('returnResponse should be called\ 1284 | \ by the last runContainer onComplete callback execution only.');\n return;\n\ 1285 | \ }\n assertThat(true).isTrue(); // Dummy to cover the case when runContainerExecutions\ 1286 | \ === runContainerExpectedExecutions.\n});\n\nrunCode(mockData);\n\ncallLater(()\ 1287 | \ => {\n assertThat(claimRequestWasCalled).isTrue();\n assertApi('setResponseStatus').wasCalledWith(200);\n\ 1288 | \ assertThat(runContainerExecutions).isEqualTo(runContainerExpectedExecutions);\n\ 1289 | });" 1290 | - name: Should fallback to 200 if Response Status Code is absent from the data object 1291 | code: "mockData.acceptMultipleEvents = true;\n\nObject.delete(mockData, 'responseStatusCode');\n\ 1292 | \nmock('getRequestPath', '/data');\nmock('requestMethod', 'POST');\nmock('getRequestBody',\ 1293 | \ '[{\"event\":\"page_view\",\"client_id\":\"client_id\"},{\"event\":\"view_item\"\ 1294 | ,\"client_id\":\"client_id\"}]');\n\n/* \n For some reason when we use \"assertApi('claimRequest').wasCalled()\"\ 1295 | \ AND we run all the tests,\n it produces the following error \"Tried to claim\ 1296 | \ a request after a Client had returned. Calling claimRequest from a callback\ 1297 | \ is not supported.\"\n If we run only this single test, the error does not occur.\n\ 1298 | \ A workaround is to mock 'claimRequest' API and make a dummy assertion in the\ 1299 | \ mocked function. This way we make sure it's been called.\n*/\nlet claimRequestWasCalled;\n\ 1300 | mock('claimRequest', () => {\n claimRequestWasCalled = true;\n});\n\nmock('setResponseStatus',\ 1301 | \ (responseStatus) => {\n assertThat(responseStatus).isEqualTo(200);\n});\n\n\ 1302 | /*\n For some reason when we mock 'claimRequest', the following error is shown\ 1303 | \ when the test is run: 'Request must be claimed before calling runContainer.'\n\ 1304 | \ A workaround is to mock 'runContainer' and simply call its callbacks.\n*/\n\ 1305 | mock('runContainer', (eventData, onCompleteCallback, onStartCallback) => {\n \ 1306 | \ onCompleteCallback();\n});\n\nrunCode(mockData);\n\ncallLater(() => {\n assertThat(claimRequestWasCalled).isTrue();\n\ 1307 | \ assertApi('returnResponse').wasCalled();\n});" 1308 | - name: Client ID retrieval and generation (from _dcid cookie, from Event Data pre-defined 1309 | keys and from Temporary Client ID) 1310 | code: "const originalMockData = mockData;\n\nmock('getRequestPath', '/data');\n\ 1311 | mock('requestMethod', 'POST');\n\n[\n {\n description: 'Should use Client\ 1312 | \ ID from Event Model if one is present',\n mockData: {\n generateClientId:\ 1313 | \ true,\n acceptMultipleEvents: true\n },\n mock: () => {\n mock('getRequestBody',\ 1314 | \ '[{\"event\":\"page_view\",\"client_id\":\"client_id\",\"_dcid_temp\":\"_dcid_temp\"\ 1315 | },{\"event\":\"view_item\",\"_dcid\":\"_dcid\",\"_dcid_temp\":\"_dcid_temp\"}]');\n\ 1316 | \ mock('getCookieValues', []);\n },\n assert: (eventData) => {\n \ 1317 | \ assertThat(eventData.client_id).isEqualTo('client_id'); // The first found\ 1318 | \ Client ID is used for all events in the payload.\n }\n },\n {\n description:\ 1319 | \ 'Should use Client ID from _dcid cookie if present and no Client ID is present\ 1320 | \ in Event Model',\n mockData: {\n generateClientId: true,\n acceptMultipleEvents:\ 1321 | \ true\n }, \n mock: () => {\n mock('getRequestBody', '[{\"event\"\ 1322 | :\"page_view\",\"_dcid_temp\":\"_dcid_temp\"},{\"event\":\"view_item\",\"_dcid_temp\"\ 1323 | :\"_dcid_temp\"}]');\n mock('getCookieValues', ['_dcid_from_cookie']);\n\ 1324 | \ },\n assert: (eventData) => {\n assertThat(eventData.client_id).isEqualTo('_dcid_from_cookie');\n\ 1325 | \ }\n },\n { \n description: 'Should use Client ID from temporary Client\ 1326 | \ ID if option is enabled, and it is present in Event Model and, _dcid cookie\ 1327 | \ or Client ID in Event Data do not exist',\n mockData: {\n generateClientId:\ 1328 | \ true,\n acceptMultipleEvents: true\n },\n mock: () => {\n mock('getRequestBody',\ 1329 | \ '[{\"event\":\"page_view\",\"_dcid_temp\":\"_dcid_temp\"},{\"event\":\"view_item\"\ 1330 | ,\"_dcid_temp\":\"_dcid_temp\"}]');\n mock('getCookieValues', []);\n },\n\ 1331 | \ assert: (eventData) => {\n assertThat(eventData.client_id).isEqualTo('_dcid_temp');\n\ 1332 | \ }\n },\n { \n description: 'Should generate a random Client ID if option\ 1333 | \ is enabled, and _dcid cookie or Client ID in Event Data or temporary Client\ 1334 | \ ID do not exist',\n mockData: {\n generateClientId: true,\n acceptMultipleEvents:\ 1335 | \ true\n },\n mock: () => {\n mock('getRequestBody', '[{\"event\":\"\ 1336 | page_view\"},{\"event\":\"view_item\"}]');\n mock('getCookieValues', []);\n\ 1337 | \ },\n assert: (eventData) => {\n assertThat(eventData.client_id).isEqualTo('dcid.1.1747945830456.123456789');\n\ 1338 | \ }\n },\n { \n description: 'Should NOT generate a random Client ID or\ 1339 | \ use temporary Client ID if option is disabled',\n mockData: {\n generateClientId:\ 1340 | \ false,\n acceptMultipleEvents: true\n },\n mock: () => {\n mock('getRequestBody',\ 1341 | \ '[{\"event\":\"page_view\"},{\"event\":\"view_item\"}]');\n mock('getCookieValues',\ 1342 | \ []);\n },\n assert: (eventData) => {\n assertThat(eventData.client_id).isFalsy();\n\ 1343 | \ }\n }\n].forEach(scenario => {\n const copyMockData = JSON.parse(JSON.stringify(originalMockData));\n\ 1344 | \ mergeObj(copyMockData, scenario.mockData);\n \n scenario.mock();\n \n /*\ 1345 | \ \n For some reason when we use \"assertApi('claimRequest').wasCalled()\"\ 1346 | \ AND we run all the tests,\n it produces the following error \"Tried to claim\ 1347 | \ a request after a Client had returned. Calling claimRequest from a callback\ 1348 | \ is not supported.\"\n If we run only this single test, the error does not\ 1349 | \ occur.\n A workaround is to mock 'claimRequest' API and make a dummy assertion\ 1350 | \ in the mocked function. This way we make sure it's been called.\n */\n let\ 1351 | \ claimRequestWasCalled;\n mock('claimRequest', () => {\n claimRequestWasCalled\ 1352 | \ = true;\n });\n \n mock('setResponseStatus', (responseStatus) => {\n assertThat(responseStatus).isEqualTo(200);\n\ 1353 | \ });\n \n /*\n For some reason when we mock 'claimRequest', the following\ 1354 | \ error is shown when the test is run: 'Request must be claimed before calling\ 1355 | \ runContainer.'\n A workaround is to mock 'runContainer' and simply call its\ 1356 | \ callbacks.\n */\n mock('runContainer', (eventData, onCompleteCallback, onStartCallback)\ 1357 | \ => {\n assertThat(eventData.hasOwnProperty('_temp_dcid')).isFalse();\n \ 1358 | \ scenario.assert(eventData);\n onCompleteCallback(); \n });\n \n runCode(copyMockData);\n\ 1359 | \ \n callLater(() => {\n assertThat(claimRequestWasCalled).isTrue();\n \ 1360 | \ assertApi('returnResponse').wasCalled();\n });\n});" 1361 | setup: |- 1362 | const JSON = require('JSON'); 1363 | const Object = require('Object'); 1364 | const callLater = require('callLater'); 1365 | 1366 | function mergeObj(target, source) { 1367 | for (const key in source) { 1368 | if (source.hasOwnProperty(key)) target[key] = source[key]; 1369 | } 1370 | return target; 1371 | } 1372 | 1373 | const mockData = { 1374 | responseStatusCode: 200, 1375 | generateClientId: true, 1376 | responseBody: 'timestamp', 1377 | prolongCookies: true, 1378 | httpOnlyCookie: false, 1379 | responseBodyGet: false, 1380 | acceptMultipleEvents: false, 1381 | exposeFPIDCookie: false 1382 | }; 1383 | 1384 | mock('getRequestHeader', (header) => { 1385 | if (header === 'trace-id') return 'expectedTraceId'; 1386 | }); 1387 | 1388 | mock('getTimestampMillis', 1747945830456); 1389 | 1390 | mock('generateRandom', 123456789); 1391 | 1392 | 1393 | ___NOTES___ 1394 | 1395 | Created on 21/03/2021, 11:24:30 1396 | 1397 | --------------------------------------------------------------------------------