@hermoso/research 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +56 -2
- package/package.json +48 -4
- package/src/dedupe.js +24 -0
- package/src/discovery.js +113 -0
- package/src/index.js +15 -0
- package/src/llm.js +28 -0
- package/src/longevity.js +40 -0
- package/src/normalize.js +169 -0
- package/src/provider.js +17 -0
- package/src/providers/hosted.js +140 -0
- package/src/providers/memory.js +31 -0
- package/src/research.js +124 -0
- package/src/resolve-page.js +47 -0
- package/src/teardown.js +86 -0
- package/src/tools.js +89 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Hermoso
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hermoso/research
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Ad research for AI agents and scripts: search the Meta, Google and LinkedIn ad libraries, find a company's competitors, pull a brand's longest-running ads, and tear down their playbook into angles you can use.
|
|
4
|
+
|
|
5
|
+
What is in here is the logic:
|
|
6
|
+
|
|
7
|
+
- **Page resolution.** A brand is matched to its Meta page using the Instagram handle its own website links to; an uncertain match returns no ads and a note instead of a namesake's ads.
|
|
8
|
+
- **Dedupe.** An ad is a duplicate only if both its copy and its asset file match, so A/B tests of the same caption are kept.
|
|
9
|
+
- **Longevity.** Ads are sorted longest-running first and labelled (testing, likely profitable, proven, evergreen): an advertiser keeps paying for what works.
|
|
10
|
+
- **Clean ads.** Catalog-ad template tokens never reach the reader, an advertiser is never titled by a bare id, and namesakes from a name-only library are filtered out.
|
|
11
|
+
- **Discovery and teardowns** through the text model in `@hermoso/core`.
|
|
12
|
+
|
|
13
|
+
## Data providers
|
|
14
|
+
|
|
15
|
+
Where the ads come from is an adapter. The default is the hosted Hermoso API (`HERMOSO_API_KEY`): it calls the public tool endpoints (`POST /v1/tools/search_meta_ads`, `search_google_ads`, `search_linkedin_ads`, the same tools the hosted MCP server lists) with their published arguments, and maps each result into the schema below. It reads only neutral row fields (`advertiser`, `headline`, `body` or `description`, `cta`, `link`, `url`, `format`, `media`, `thumb`, `image`, `video`, `dates` or `startDate`/`endDate`, `impressions`), so any server that answers in that shape works. To use your own source, implement three methods:
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { createResearch, defineProvider } from '@hermoso/research';
|
|
19
|
+
|
|
20
|
+
const mine = defineProvider({
|
|
21
|
+
id: 'mine',
|
|
22
|
+
platforms: ['meta', 'google', 'linkedin'],
|
|
23
|
+
async searchAds({ platform, query, country, status, mediaType, cursor, limit }) { return { ads: [], cursor: null }; },
|
|
24
|
+
async companyAds({ platform, pageId, company, domain, country, status, mediaType, cursor, limit }) { return { ads: [], cursor: null }; },
|
|
25
|
+
async findAdvertisers({ platform, query, domain }) { return { advertisers: [] }; },
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
const research = createResearch({ provider: mine });
|
|
29
|
+
const { ads } = await research.pullCompetitorAds({ name: 'Northwind Coffee', domain: 'northwind.example', platforms: ['meta', 'google'] });
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Every provider answers in one neutral ad schema, owned by this package (`AD_FIELDS`, `normalizeAd()`):
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
{
|
|
36
|
+
id, platform, // 'meta' | 'google' | 'linkedin'
|
|
37
|
+
advertiser, advertiserId, domain,
|
|
38
|
+
headline, body, cta, link,
|
|
39
|
+
media: [{ type: 'image' | 'video', url, poster }],
|
|
40
|
+
format, // 'image', 'video', 'carousel', 'text', …
|
|
41
|
+
startDate, endDate, // 'YYYY-MM-DD' or null
|
|
42
|
+
active, // true, false, or null when the source does not say
|
|
43
|
+
runDays, live, // derived from the dates (a source that only knows the run length may set runDays)
|
|
44
|
+
platforms, url, impressions,
|
|
45
|
+
catalogAd, // derived: a dynamic product ad whose copy is a template
|
|
46
|
+
}
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
A provider returns any subset of these fields; the package fills in the derived ones, fills or drops catalog template tokens, and never titles an ad by a bare advertiser id. A media item may also carry `headline` and `body` (a carousel card's own words), used to fill catalog templates. An advertiser is `{ id, name, domain?, instagram?, likes?, category?, confirmed? }`, where `confirmed` means your source matched that page to the brand on evidence. A `cursor` is opaque: return whatever string your source needs for the next page, or null when there is none.
|
|
50
|
+
|
|
51
|
+
`memoryProvider({ ads, advertisers })` is a fixture provider for tests and demos, and the reference for writing your own.
|
|
52
|
+
|
|
53
|
+
## Tools
|
|
54
|
+
|
|
55
|
+
`getTools()` returns `find_competitors`, `search_ad_library`, `find_advertiser`, `pull_competitor_ads`, `competitor_teardown` and `mine_angles` for `@hermoso/agent` and `@hermoso/mcp`.
|
|
56
|
+
|
|
57
|
+
Apache-2.0
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hermoso/research",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Ad research for AI agents: search the Meta, Google and LinkedIn ad libraries, find competitors, pull a brand's longest-running ads, and tear down their playbook.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"ad-library",
|
|
7
|
+
"ad-research",
|
|
8
|
+
"competitor-analysis",
|
|
9
|
+
"meta-ads",
|
|
10
|
+
"google-ads",
|
|
11
|
+
"linkedin-ads",
|
|
12
|
+
"ai-agents",
|
|
13
|
+
"mcp",
|
|
14
|
+
"hermoso",
|
|
15
|
+
"open-source"
|
|
16
|
+
],
|
|
17
|
+
"homepage": "https://github.com/hermoso-ai/hermoso/tree/main/packages/research#readme",
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/hermoso-ai/hermoso/issues"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/hermoso-ai/hermoso.git",
|
|
24
|
+
"directory": "packages/research"
|
|
25
|
+
},
|
|
26
|
+
"license": "Apache-2.0",
|
|
27
|
+
"author": "Hermoso <hello@hermoso.ai>",
|
|
28
|
+
"type": "module",
|
|
29
|
+
"main": "./src/index.js",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": "./src/index.js"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"src",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test test/*.test.js"
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"@hermoso/core": "^0.1.0"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=22.5"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/dedupe.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
|
|
2
|
+
const assetKey = (url) => {
|
|
3
|
+
if (!url) return '';
|
|
4
|
+
try { return new URL(url).pathname.split('/').filter(Boolean).pop() || ''; } catch { return String(url).split('?')[0].split('/').pop() || ''; }
|
|
5
|
+
};
|
|
6
|
+
const copyKey = (a) => [a.headline, a.body].map((s) => String(s || '').toLowerCase().replace(/\s+/g, ' ').trim()).join('|');
|
|
7
|
+
|
|
8
|
+
export function adSignature(ad) {
|
|
9
|
+
if (!ad) return '';
|
|
10
|
+
return `${ad.platform || ''}::${copyKey(ad)}::${assetKey(ad.media?.[0]?.url)}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Keep the first ad of each signature (sort first if you want the longest-running copy kept). */
|
|
14
|
+
export function dedupeAds(ads) {
|
|
15
|
+
const seen = new Set();
|
|
16
|
+
const out = [];
|
|
17
|
+
for (const a of Array.isArray(ads) ? ads : []) {
|
|
18
|
+
const sig = adSignature(a);
|
|
19
|
+
if (sig && seen.has(sig)) continue;
|
|
20
|
+
seen.add(sig);
|
|
21
|
+
out.push(a);
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
package/src/discovery.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
|
|
2
|
+
import * as core from '@hermoso/core';
|
|
3
|
+
|
|
4
|
+
const fetchSafe = (...a) => (core.http?.fetchSafe ?? core.fetchSafe)(...a);
|
|
5
|
+
import { askJson } from './llm.js';
|
|
6
|
+
|
|
7
|
+
export const AGG_RE = /(^|\.)(wikipedia|reddit|quora|youtube|capterra|g2|getapp|softwareadvice|trustpilot|trustradius|crunchbase|owler|similarweb|glassdoor|indeed|linkedin|facebook|instagram|twitter|tiktok|pinterest|medium|substack|forbes|inc|entrepreneur|businessinsider|techcrunch|cnbc|nytimes|investopedia|producthunt|yelp|tripadvisor|wikihow)\.[a-z.]+$/i;
|
|
8
|
+
export const MARKETPLACE_RE = /(^|\.)(amazon|ebay|walmart|target|etsy|aliexpress|bestbuy)\.[a-z.]+$/i;
|
|
9
|
+
|
|
10
|
+
export const MODES = Object.freeze(['competitors', 'inspiration']);
|
|
11
|
+
|
|
12
|
+
export const COMPETITORS_SYSTEM = `You identify a company's closest competitors and similar brands for advertising inspiration: brands whose ads someone studying the target company would want to copy or remix.
|
|
13
|
+
|
|
14
|
+
Rules:
|
|
15
|
+
- Return REAL, currently-operating brands you are confident exist. Never invent brands or domains.
|
|
16
|
+
- Give each brand's primary marketing root domain, lowercase, no protocol, no "www", no path (e.g. "example.com").
|
|
17
|
+
- "kind" is "competitor" for a head-to-head rival, or "similar" for an adjacent brand in the same space worth drawing inspiration from.
|
|
18
|
+
- "reason" is one short phrase (max 8 words) on why it is relevant.
|
|
19
|
+
- EXCLUDE the input company itself; broad marketplaces that resell many brands unless one is a true direct competitor; and review, listicle, aggregator and social sites.
|
|
20
|
+
- Order by relevance, most direct competitors first.
|
|
21
|
+
- If page text is provided, use it to understand what the company sells; never return the publishers that merely write about it.`;
|
|
22
|
+
|
|
23
|
+
export const INSPIRATION_SYSTEM = `You curate the most copyable ad creative relevant to a given company, for a marketer seeking inspiration, not only direct competitors.
|
|
24
|
+
|
|
25
|
+
Return a mix of:
|
|
26
|
+
- direct competitors (kind: "competitor"),
|
|
27
|
+
- adjacent brands in the same space (kind: "similar"),
|
|
28
|
+
- and non-competitor brands known for excellent, distinctive advertising this company could learn from: same audience, aesthetic, price tier or marketing playbook (kind: "adjacent").
|
|
29
|
+
|
|
30
|
+
Rules:
|
|
31
|
+
- Return REAL, currently-operating brands you are confident exist, with their primary marketing root domain (lowercase, no protocol, www or path).
|
|
32
|
+
- Prefer brands whose creative is genuinely worth copying, even when they are not competitors.
|
|
33
|
+
- "reason" is one short phrase (max 8 words) on why their ads are worth studying for this company.
|
|
34
|
+
- EXCLUDE broad marketplaces unless a true peer, and review, listicle, aggregator and social sites.
|
|
35
|
+
- Order by how inspiring and relevant their creative is for this company.`;
|
|
36
|
+
|
|
37
|
+
export const BRANDS_SCHEMA = {
|
|
38
|
+
type: 'object', additionalProperties: false,
|
|
39
|
+
properties: {
|
|
40
|
+
company: { type: 'string', description: 'the target company name' },
|
|
41
|
+
brands: {
|
|
42
|
+
type: 'array',
|
|
43
|
+
items: {
|
|
44
|
+
type: 'object', additionalProperties: false,
|
|
45
|
+
properties: {
|
|
46
|
+
name: { type: 'string' },
|
|
47
|
+
domain: { type: 'string' },
|
|
48
|
+
kind: { type: 'string', enum: ['competitor', 'similar', 'adjacent'] },
|
|
49
|
+
reason: { type: 'string' },
|
|
50
|
+
},
|
|
51
|
+
required: ['name', 'domain', 'kind', 'reason'],
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
required: ['company', 'brands'],
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** example.com from any URL-ish string; '' when it is not a domain. */
|
|
59
|
+
export function cleanDomain(v) {
|
|
60
|
+
const s = String(v || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/^www\./, '').split(/[/?#\s]/)[0];
|
|
61
|
+
return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(s) ? s : '';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Readable text and title from a home page, capped, for grounding. */
|
|
65
|
+
export function pageSummary(html, max = 2500) {
|
|
66
|
+
const s = String(html || '');
|
|
67
|
+
const title = (s.match(/<title[^>]*>([^<]*)<\/title>/i) || [])[1] || '';
|
|
68
|
+
const desc = (s.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["']/i) || [])[1] || '';
|
|
69
|
+
const text = s.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<noscript[\s\S]*?<\/noscript>/gi, ' ')
|
|
70
|
+
.replace(/<[^>]+>/g, ' ').replace(/ /g, ' ').replace(/&/g, '&').replace(/\s+/g, ' ').trim();
|
|
71
|
+
return [title && `Title: ${title.trim()}`, desc && `Description: ${desc.trim()}`, text && `Text: ${text.slice(0, max)}`].filter(Boolean).join('\n');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Clean, dedupe and filter the model's brands. Pure. */
|
|
75
|
+
export function cleanCandidates(brands, { domain = '', mode = 'competitors', limit = 12 } = {}) {
|
|
76
|
+
const self = cleanDomain(domain);
|
|
77
|
+
const seen = new Set();
|
|
78
|
+
const out = [];
|
|
79
|
+
for (const b of Array.isArray(brands) ? brands : []) {
|
|
80
|
+
const d = cleanDomain(b?.domain);
|
|
81
|
+
const name = String(b?.name || '').trim();
|
|
82
|
+
if (!d || !name || AGG_RE.test(d) || seen.has(d)) continue;
|
|
83
|
+
if (MARKETPLACE_RE.test(d) && b.kind !== 'competitor') continue;
|
|
84
|
+
if (self && (d === self || d.endsWith('.' + self))) continue;
|
|
85
|
+
seen.add(d);
|
|
86
|
+
out.push({ name, domain: d, kind: ['competitor', 'similar', 'adjacent'].includes(b.kind) ? b.kind : 'similar', reason: String(b.reason || '').trim() });
|
|
87
|
+
}
|
|
88
|
+
if (mode === 'inspiration' && self) out.unshift({ name: '', domain: self, kind: 'self', reason: 'your own ads, for reference', seed: true });
|
|
89
|
+
return out.slice(0, limit + (mode === 'inspiration' && self ? 1 : 0));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function findCompetitors({ domain = '', description = '', mode = 'competitors', limit = 12, text, fetchPage } = {}) {
|
|
93
|
+
if (!MODES.includes(mode)) throw new Error(`Unknown mode "${mode}". Use ${MODES.join(' or ')}.`);
|
|
94
|
+
const d = cleanDomain(domain);
|
|
95
|
+
if (!d && !String(description).trim()) throw new Error('Give a website domain or a short description of the company.');
|
|
96
|
+
let grounding = '';
|
|
97
|
+
if (d) {
|
|
98
|
+
try {
|
|
99
|
+
const get = fetchPage || (async (url) => { const r = await fetchSafe(url, { headers: { 'user-agent': 'Mozilla/5.0 (compatible; hermoso-research)' } }); return r.ok ? r.text() : ''; });
|
|
100
|
+
grounding = pageSummary(await get(`https://${d}/`));
|
|
101
|
+
} catch { grounding = ''; }
|
|
102
|
+
}
|
|
103
|
+
const user = [
|
|
104
|
+
d && `Company website: ${d}`,
|
|
105
|
+
description && `About the company: ${String(description).slice(0, 1500)}`,
|
|
106
|
+
grounding && `Home page:\n${grounding}`,
|
|
107
|
+
`Return up to ${limit} brands.`,
|
|
108
|
+
].filter(Boolean).join('\n\n');
|
|
109
|
+
const json = await askJson({ system: mode === 'inspiration' ? INSPIRATION_SYSTEM : COMPETITORS_SYSTEM, user, schema: BRANDS_SCHEMA, op: 'research.find_competitors', text });
|
|
110
|
+
const candidates = cleanCandidates(json.brands, { domain: d, mode, limit });
|
|
111
|
+
if (mode === 'inspiration' && candidates[0]?.seed) candidates[0].name = json.company || d;
|
|
112
|
+
return { company: json.company || d || null, mode, candidates };
|
|
113
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { createResearch } from './research.js';
|
|
2
|
+
export { createResearchTools } from './tools.js';
|
|
3
|
+
export { defineProvider, PLATFORMS } from './provider.js';
|
|
4
|
+
export { hostedProvider, HOSTED_TOOLS } from './providers/hosted.js';
|
|
5
|
+
export { memoryProvider } from './providers/memory.js';
|
|
6
|
+
export { normalizeAd, normalizeAds, normalizeAdvertiser, advertiserLabel, advertiserIsBrand, fillTemplate, toIsoDate, runDays, AD_FIELDS, ADVERTISER_FIELDS } from './normalize.js';
|
|
7
|
+
export { dedupeAds, adSignature } from './dedupe.js';
|
|
8
|
+
export { sortAds, longevityTier, liveLabel, LONGEVITY_TIERS, SORTS } from './longevity.js';
|
|
9
|
+
export { resolvePage, scorePage, instagramFromHtml, CONFIDENT } from './resolve-page.js';
|
|
10
|
+
export { findCompetitors, cleanCandidates, cleanDomain, pageSummary, AGG_RE, MARKETPLACE_RE } from './discovery.js';
|
|
11
|
+
export { competitorTeardown, mineAngles, adLine, HOOK_TYPES } from './teardown.js';
|
|
12
|
+
|
|
13
|
+
import { createResearchTools } from './tools.js';
|
|
14
|
+
/** The research tools, on the default (hosted) data provider. Built on first use. */
|
|
15
|
+
export function getTools(opts) { return createResearchTools(opts); }
|
package/src/llm.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
|
|
2
|
+
import { providers as coreProviders, hooks } from '@hermoso/core';
|
|
3
|
+
|
|
4
|
+
/** Pull JSON out of whatever shape a text provider returned. Throws a specific error when there is none. */
|
|
5
|
+
export function readJson(r) {
|
|
6
|
+
if (r == null) throw new Error('The text model returned nothing.');
|
|
7
|
+
for (const k of ['json', 'output', 'data', 'parsed']) if (r[k] && typeof r[k] === 'object') return r[k];
|
|
8
|
+
const text = typeof r === 'string' ? r : r.text ?? r.content ?? '';
|
|
9
|
+
const s = String(Array.isArray(text) ? text.map((b) => b?.text || '').join('') : text).trim();
|
|
10
|
+
const body = s.replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, '');
|
|
11
|
+
const at = body.search(/[{[]/);
|
|
12
|
+
if (at < 0) throw new Error('The text model did not answer with JSON.');
|
|
13
|
+
try { return JSON.parse(body.slice(at)); } catch { throw new Error('The text model answered with JSON that could not be read (it may have been cut off).'); }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function askJson({ system, user, schema, op = 'research.text', text } = {}) {
|
|
17
|
+
const provider = text || coreProviders.text;
|
|
18
|
+
const hold = await hooks.billing.reserve({ op, units: { calls: 1 }, meta: {} });
|
|
19
|
+
try {
|
|
20
|
+
const r = await provider.complete({ system, messages: [{ role: 'user', content: user }], schema });
|
|
21
|
+
const json = readJson(r);
|
|
22
|
+
await hooks.billing.settle(hold?.holdId ?? null, { units: { calls: 1 }, usage: r?.usage ?? null });
|
|
23
|
+
return json;
|
|
24
|
+
} catch (e) {
|
|
25
|
+
await hooks.billing.release(hold?.holdId ?? null);
|
|
26
|
+
throw e;
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/longevity.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const LONGEVITY_TIERS = Object.freeze([
|
|
2
|
+
Object.freeze({ min: 30, tier: 'evergreen' }),
|
|
3
|
+
Object.freeze({ min: 14, tier: 'proven' }),
|
|
4
|
+
Object.freeze({ min: 7, tier: 'likely profitable' }),
|
|
5
|
+
Object.freeze({ min: 3, tier: 'testing' }),
|
|
6
|
+
]);
|
|
7
|
+
|
|
8
|
+
export function longevityTier(days) {
|
|
9
|
+
const d = Number(days);
|
|
10
|
+
if (!Number.isFinite(d) || d < 3) return '';
|
|
11
|
+
return LONGEVITY_TIERS.find((t) => d >= t.min).tier;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** "45d live · evergreen", or "2d live" when it is too new to say. */
|
|
15
|
+
export function liveLabel(days) {
|
|
16
|
+
const d = Math.max(0, Math.round(Number(days) || 0));
|
|
17
|
+
const t = longevityTier(d);
|
|
18
|
+
return `${d}d live${t ? ` · ${t}` : ''}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const impressionsRank = (v) => {
|
|
22
|
+
if (typeof v === 'number') return v;
|
|
23
|
+
const m = String(v || '').replace(/,/g, '').match(/(\d+(?:\.\d+)?)\s*([kKmM]?)/);
|
|
24
|
+
if (!m) return -1;
|
|
25
|
+
return Number(m[1]) * (m[2].toLowerCase() === 'm' ? 1e6 : m[2].toLowerCase() === 'k' ? 1e3 : 1);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const SORTS = Object.freeze(['longest_running', 'newest', 'impressions']);
|
|
29
|
+
|
|
30
|
+
/** Sort normalized ads. Returns a new array; ties keep their original order. */
|
|
31
|
+
export function sortAds(ads, sort = 'longest_running') {
|
|
32
|
+
const list = (Array.isArray(ads) ? ads : []).map((a, i) => [a, i]);
|
|
33
|
+
const by = {
|
|
34
|
+
longest_running: (a) => a.runDays ?? -1,
|
|
35
|
+
newest: (a) => (a.startDate ? Date.parse(a.startDate) : -Infinity),
|
|
36
|
+
impressions: (a) => impressionsRank(a.impressions),
|
|
37
|
+
}[sort];
|
|
38
|
+
if (!by) throw new Error(`Unknown sort "${sort}". Use ${SORTS.join(', ')}.`);
|
|
39
|
+
return list.sort(([a, i], [b, j]) => (by(b) - by(a)) || (i - j)).map(([a]) => a);
|
|
40
|
+
}
|
package/src/normalize.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
|
|
2
|
+
import { liveLabel } from './longevity.js';
|
|
3
|
+
|
|
4
|
+
export const AD_FIELDS = Object.freeze(['id', 'platform', 'advertiser', 'advertiserId', 'domain', 'headline', 'body', 'cta', 'link', 'media', 'format', 'startDate', 'endDate', 'active', 'runDays', 'live', 'platforms', 'url', 'impressions', 'catalogAd']);
|
|
5
|
+
export const ADVERTISER_FIELDS = Object.freeze(['id', 'name', 'domain', 'instagram', 'likes', 'category', 'confirmed']);
|
|
6
|
+
|
|
7
|
+
const DAY = 86_400_000;
|
|
8
|
+
const str = (v) => (typeof v === 'string' ? v : v == null ? '' : String(v));
|
|
9
|
+
const orNull = (v) => (str(v).trim() ? str(v).trim() : null);
|
|
10
|
+
|
|
11
|
+
/** A date in any common shape (unix seconds, ms, ISO, YYYY-MM-DD) -> ISO date, or null. */
|
|
12
|
+
export function toIsoDate(v) {
|
|
13
|
+
if (v == null || v === '') return null;
|
|
14
|
+
let d;
|
|
15
|
+
if (typeof v === 'number' || /^\d+$/.test(str(v))) {
|
|
16
|
+
const n = Number(v);
|
|
17
|
+
d = new Date(n < 1e12 ? n * 1000 : n);
|
|
18
|
+
} else d = new Date(str(v));
|
|
19
|
+
return Number.isFinite(d.getTime()) ? d.toISOString().slice(0, 10) : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Whole days between start and end (or now, when the ad is still running). */
|
|
23
|
+
export function runDays(startIso, endIso, now = Date.now()) {
|
|
24
|
+
if (!startIso) return null;
|
|
25
|
+
const s = Date.parse(startIso);
|
|
26
|
+
const e = endIso ? Date.parse(endIso) : now;
|
|
27
|
+
if (!Number.isFinite(s) || !Number.isFinite(e)) return null;
|
|
28
|
+
return Math.max(0, Math.round((e - s) / DAY));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const TOKEN = /\{\{\s*([^{}]*?)\s*\}\}/g;
|
|
32
|
+
export const hasTemplateToken = (s) => typeof s === 'string' && /\{\{[^{}]*\}\}/.test(s);
|
|
33
|
+
export const CATALOG_AD_NOTE = 'Catalog (dynamic product) ad: the platform fills in each viewer’s product at delivery, so the library holds no fixed copy.';
|
|
34
|
+
const tidy = (s) => s.replace(/\s+/g, ' ').replace(/\s+([,.;:!?])/g, '$1').replace(/^[\s\-–—:|,.;·]+|[\s\-–—:|·]+$/g, '').trim();
|
|
35
|
+
const hasWords = (s) => /[\p{L}\p{N}]/u.test(s);
|
|
36
|
+
|
|
37
|
+
export function fillTemplate(text, vals = {}) {
|
|
38
|
+
if (!hasTemplateToken(text)) return text;
|
|
39
|
+
const out = tidy(str(text).replace(TOKEN, (_, raw) => {
|
|
40
|
+
const k = String(raw).toLowerCase().replace(/^(product|catalog|item)\./, '').replace(/[^a-z_]/g, '');
|
|
41
|
+
return vals[k] || (k === 'title' ? vals.name : k === 'body' ? vals.description : '') || '';
|
|
42
|
+
}));
|
|
43
|
+
return hasWords(out) ? out : '';
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const AD_ID = /^AR\d{8,}$/i;
|
|
47
|
+
const hostOf = (u) => { try { return new URL(/^https?:/i.test(u) ? u : 'https://' + u).hostname.replace(/^www\./, '').toLowerCase(); } catch { return ''; } };
|
|
48
|
+
|
|
49
|
+
/** An ad's advertiser label: its name, else its domain, else the brand searched; never a bare advertiser id. */
|
|
50
|
+
export function advertiserLabel(ad, fallback = '') {
|
|
51
|
+
const n = str(ad?.advertiser).trim();
|
|
52
|
+
const id = str(ad?.advertiserId).trim();
|
|
53
|
+
if (n && !AD_ID.test(n) && n !== id) return n;
|
|
54
|
+
return hostOf(str(ad?.domain)) || str(fallback).trim() || '';
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const MEDIA_TYPES = new Set(['image', 'video']);
|
|
58
|
+
const looksVideo = (u) => /\.(mp4|mov|webm|m3u8)(\?|$)/i.test(u);
|
|
59
|
+
|
|
60
|
+
function mediaOf(list) {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const m of Array.isArray(list) ? list : []) {
|
|
63
|
+
const item = typeof m === 'string' ? { url: m } : m;
|
|
64
|
+
const url = str(item?.url).trim();
|
|
65
|
+
if (!url) continue;
|
|
66
|
+
const type = MEDIA_TYPES.has(item.type) ? item.type : looksVideo(url) ? 'video' : 'image';
|
|
67
|
+
out.push(type === 'video' ? { type, url, poster: orNull(item.poster) } : { type, url });
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* One ad in the schema above, from whatever subset a provider returned. Returns null for something that is not an ad.
|
|
74
|
+
* opts: { platform, fallbackName, now }
|
|
75
|
+
*/
|
|
76
|
+
export function normalizeAd(input, { platform, fallbackName = '', now = Date.now() } = {}) {
|
|
77
|
+
if (!input || typeof input !== 'object') return null;
|
|
78
|
+
const cards = (Array.isArray(input.media) ? input.media : []).filter((m) => m && typeof m === 'object');
|
|
79
|
+
const media = mediaOf(input.media);
|
|
80
|
+
const advertiser = advertiserLabel(input, fallbackName);
|
|
81
|
+
|
|
82
|
+
const real = (v) => (typeof v === 'string' && v && !hasTemplateToken(v) && hasWords(v) ? v : '');
|
|
83
|
+
const vals = {
|
|
84
|
+
brand: advertiser,
|
|
85
|
+
name: cards.map((c) => real(c.headline)).find(Boolean) || real(input.headline) || '',
|
|
86
|
+
description: cards.map((c) => real(c.body)).find(Boolean) || '',
|
|
87
|
+
};
|
|
88
|
+
const rawBody = str(input.body);
|
|
89
|
+
const rawHeadline = str(input.headline);
|
|
90
|
+
const catalogAd = input.catalogAd === true || hasTemplateToken(rawBody) || hasTemplateToken(rawHeadline);
|
|
91
|
+
let body = fillTemplate(rawBody, vals);
|
|
92
|
+
if (catalogAd && !body) body = vals.description || vals.name || CATALOG_AD_NOTE;
|
|
93
|
+
|
|
94
|
+
const startDate = toIsoDate(input.startDate);
|
|
95
|
+
const endDate = toIsoDate(input.endDate);
|
|
96
|
+
const active = typeof input.active === 'boolean' ? input.active : null;
|
|
97
|
+
const given = Number(input.runDays);
|
|
98
|
+
const days = startDate ? runDays(startDate, active === true ? null : endDate, now)
|
|
99
|
+
: input.runDays != null && Number.isFinite(given) && given >= 0 ? Math.round(given) : null;
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
id: orNull(input.id),
|
|
103
|
+
platform: platform || str(input.platform) || null,
|
|
104
|
+
advertiser,
|
|
105
|
+
advertiserId: orNull(input.advertiserId),
|
|
106
|
+
domain: orNull(input.domain),
|
|
107
|
+
headline: fillTemplate(rawHeadline, vals),
|
|
108
|
+
body,
|
|
109
|
+
cta: orNull(input.cta),
|
|
110
|
+
link: orNull(input.link),
|
|
111
|
+
media,
|
|
112
|
+
format: str(input.format).toLowerCase() || (media.length > 1 ? 'carousel' : media[0]?.type || 'text'),
|
|
113
|
+
startDate,
|
|
114
|
+
endDate,
|
|
115
|
+
active,
|
|
116
|
+
runDays: days,
|
|
117
|
+
live: days == null ? null : liveLabel(days),
|
|
118
|
+
platforms: Array.isArray(input.platforms) ? input.platforms.map((p) => str(p).toLowerCase()).filter(Boolean) : [],
|
|
119
|
+
url: orNull(input.url),
|
|
120
|
+
impressions: input.impressions ?? null,
|
|
121
|
+
catalogAd,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Normalize a provider's ads for a platform, dropping anything that is not readable as an ad. */
|
|
126
|
+
export function normalizeAds(platform, rows, opts = {}) {
|
|
127
|
+
if (!['meta', 'google', 'linkedin'].includes(platform)) throw new Error(`Unknown ad platform "${platform}". Use meta, google or linkedin.`);
|
|
128
|
+
return (Array.isArray(rows) ? rows : [])
|
|
129
|
+
.map((r) => normalizeAd(r, { ...opts, platform }))
|
|
130
|
+
.filter((a) => a && (a.id || a.body || a.headline || a.media.length || a.url));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** One advertiser (a page or account in a library): { id, name, domain, instagram, likes, category, confirmed }. */
|
|
134
|
+
export function normalizeAdvertiser(input) {
|
|
135
|
+
if (!input || typeof input !== 'object') return null;
|
|
136
|
+
const id = orNull(input.id);
|
|
137
|
+
const name = str(input.name).trim();
|
|
138
|
+
if (!id && !name) return null;
|
|
139
|
+
const raw = input.likes ?? input.followers;
|
|
140
|
+
const likes = raw == null || raw === '' ? null : Number(raw);
|
|
141
|
+
return {
|
|
142
|
+
id,
|
|
143
|
+
name,
|
|
144
|
+
domain: orNull(input.domain),
|
|
145
|
+
instagram: orNull(str(input.instagram).replace(/^@/, '')),
|
|
146
|
+
likes: Number.isFinite(likes) ? likes : null,
|
|
147
|
+
category: orNull(input.category),
|
|
148
|
+
confirmed: input.confirmed === true,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const flat = (s) => str(s).normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/&/g, ' and ').replace(/[^a-z0-9]+/g, ' ').trim();
|
|
153
|
+
const SUFFIX = new Set(['inc', 'llc', 'ltd', 'limited', 'plc', 'corp', 'corporation', 'co', 'company', 'holdings', 'holding', 'group', 'international', 'intl', 'global', 'the', 'uk', 'us', 'usa', 'gmbh', 'ag', 'sa', 'official', 'brands', 'brand']);
|
|
154
|
+
const baseOf = (h) => h.split('.').slice(-2).join('.');
|
|
155
|
+
const NEUTRAL = /(^|\.)(linkedin|facebook|instagram|twitter|x|youtube|tiktok|apple|google|bit|lnkd|goo|t)\.(com|in|ly|gl|co|me)$/i;
|
|
156
|
+
|
|
157
|
+
export function advertiserIsBrand(ad, companyName, domain = '') {
|
|
158
|
+
const brand = flat(companyName);
|
|
159
|
+
const adv = flat(ad?.advertiser);
|
|
160
|
+
const dBase = domain ? baseOf(hostOf(domain)) : '';
|
|
161
|
+
const dest = hostOf(str(ad?.link));
|
|
162
|
+
const landsOnBrand = !!(dBase && dest && (dest === dBase || dest.endsWith('.' + dBase)));
|
|
163
|
+
if (landsOnBrand) return true;
|
|
164
|
+
if (!brand || !adv) return false;
|
|
165
|
+
const bw = brand.split(' '); const aw = adv.split(' ');
|
|
166
|
+
const exact = aw.length >= bw.length && bw.every((w, i) => aw[i] === w) && aw.slice(bw.length).every((w) => SUFFIX.has(w));
|
|
167
|
+
const landsElsewhere = !!(dest && !NEUTRAL.test(dest) && dBase && !landsOnBrand);
|
|
168
|
+
return exact && !landsElsewhere;
|
|
169
|
+
}
|
package/src/provider.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
|
|
2
|
+
export const PLATFORMS = Object.freeze(['meta', 'google', 'linkedin']);
|
|
3
|
+
const METHODS = ['searchAds', 'companyAds', 'findAdvertisers'];
|
|
4
|
+
|
|
5
|
+
/** Validate an adapter and fill in its defaults. Throws with a sentence naming what is missing. */
|
|
6
|
+
export function defineProvider(impl) {
|
|
7
|
+
if (!impl || typeof impl !== 'object') throw new TypeError('A research data provider must be an object.');
|
|
8
|
+
const missing = METHODS.filter((m) => typeof impl[m] !== 'function');
|
|
9
|
+
if (missing.length) throw new TypeError(`Research data provider "${impl.id || 'unnamed'}" is missing: ${missing.join(', ')}.`);
|
|
10
|
+
const platforms = Array.isArray(impl.platforms) && impl.platforms.length ? impl.platforms : [...PLATFORMS];
|
|
11
|
+
return { ...impl, id: impl.id || 'custom', platforms };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function assertPlatform(provider, platform) {
|
|
15
|
+
if (!PLATFORMS.includes(platform)) throw new Error(`Unknown ad platform "${platform}". Use ${PLATFORMS.join(', ')}.`);
|
|
16
|
+
if (!provider.platforms.includes(platform)) throw new Error(`The "${provider.id}" data provider does not read the ${platform} ad library.`);
|
|
17
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
|
|
2
|
+
import * as core from '@hermoso/core';
|
|
3
|
+
import { defineProvider } from '../provider.js';
|
|
4
|
+
import { normalizeAds, toIsoDate } from '../normalize.js';
|
|
5
|
+
|
|
6
|
+
/** The public tool behind each library. */
|
|
7
|
+
export const HOSTED_TOOLS = Object.freeze({ meta: 'search_meta_ads', google: 'search_google_ads', linkedin: 'search_linkedin_ads' });
|
|
8
|
+
|
|
9
|
+
const DAY = 86_400_000;
|
|
10
|
+
const MAX_PAGE = 25;
|
|
11
|
+
const str = (v) => (typeof v === 'string' ? v : v == null ? '' : String(v));
|
|
12
|
+
const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v != null && v !== ''));
|
|
13
|
+
const pageSize = (n) => Math.min(MAX_PAGE, Math.max(1, Math.round(Number(n)) || MAX_PAGE));
|
|
14
|
+
const nextCursor = (d) => (typeof d?.cursor === 'string' && d.cursor ? d.cursor : null);
|
|
15
|
+
const withCursor = (args, cursor) => (typeof cursor === 'string' && cursor ? { ...args, cursor } : args);
|
|
16
|
+
|
|
17
|
+
async function callTool(client, name, args) {
|
|
18
|
+
const path = `/v1/tools/${encodeURIComponent(name)}`;
|
|
19
|
+
const body = clean(args);
|
|
20
|
+
let out;
|
|
21
|
+
if (typeof client.request === 'function') out = await client.request('POST', path, { body });
|
|
22
|
+
else if (typeof client.post === 'function') out = await client.post(path, body);
|
|
23
|
+
else if (typeof client.callTool === 'function') out = await client.callTool(name, body);
|
|
24
|
+
else throw new Error('The hosted client has no request, post or callTool method.');
|
|
25
|
+
const data = out && typeof out === 'object' && out.object === 'tool_result' ? out.data : out;
|
|
26
|
+
return data && typeof data === 'object' ? data : {};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A tool's run line -> neutral dates. Two shapes are published: "Mar 1 -> now · 121d" (the day count is exact, the
|
|
31
|
+
* dates carry no year) and "2026-04-01 → 2026-05-01". From the first, a running ad's start is counted back from today
|
|
32
|
+
* and an ended ad keeps its run length with no dates, rather than guessing a year.
|
|
33
|
+
*/
|
|
34
|
+
export function readRunLine(line, now = Date.now()) {
|
|
35
|
+
const s = str(line).trim();
|
|
36
|
+
if (!s) return {};
|
|
37
|
+
const [from = '', to = ''] = s.replace(/·.*$/, '').split(/\s*(?:->|→)\s*/);
|
|
38
|
+
const count = /·\s*(\d+)\s*d\s*$/.exec(s);
|
|
39
|
+
if (count) {
|
|
40
|
+
const days = Number(count[1]);
|
|
41
|
+
return /^now$/i.test(to.trim()) ? { startDate: toIsoDate(now - days * DAY), runDays: days } : { runDays: days, active: false };
|
|
42
|
+
}
|
|
43
|
+
return { startDate: toIsoDate(from.trim()), endDate: toIsoDate(to.trim()) };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One search-tool row -> the fields normalizeAd() takes. Only neutral row fields are read, the same set for every
|
|
48
|
+
* library: id (or adId, the ad's id in its library), advertiser, headline, body (or description), cta, link, url (or
|
|
49
|
+
* libraryUrl: the ad's own page in its library), format,
|
|
50
|
+
* media / thumb / image / video (urls), dates (a run line) or startDate / endDate, and impressions. A field the
|
|
51
|
+
* server does not send is simply left empty.
|
|
52
|
+
*/
|
|
53
|
+
export function toolRowToAd(r, { platform, status, domain, now = Date.now() } = {}) {
|
|
54
|
+
const run = readRunLine(r.dates, now);
|
|
55
|
+
const video = r.video || (r.thumb && r.media && r.thumb !== r.media ? r.media : null);
|
|
56
|
+
const poster = video ? (r.video ? r.image || r.thumb : r.thumb) || null : null;
|
|
57
|
+
const still = video ? null : r.image || r.media || r.thumb;
|
|
58
|
+
const startDate = r.startDate || run.startDate;
|
|
59
|
+
const endDate = r.endDate || run.endDate;
|
|
60
|
+
const id = r.id ?? r.adId;
|
|
61
|
+
return {
|
|
62
|
+
...(id != null && id !== '' ? { id: String(id) } : {}),
|
|
63
|
+
advertiser: r.advertiser,
|
|
64
|
+
...(domain ? { domain } : {}),
|
|
65
|
+
headline: r.headline,
|
|
66
|
+
body: r.body ?? r.description,
|
|
67
|
+
cta: r.cta,
|
|
68
|
+
link: r.link,
|
|
69
|
+
url: r.url || r.libraryUrl,
|
|
70
|
+
format: r.format,
|
|
71
|
+
media: video ? [{ type: 'video', url: video, poster }] : still ? [{ type: 'image', url: still }] : [],
|
|
72
|
+
...(startDate ? { startDate } : {}),
|
|
73
|
+
...(endDate ? { endDate } : {}),
|
|
74
|
+
...(run.runDays != null ? { runDays: run.runDays } : {}),
|
|
75
|
+
active: platform === 'meta' && status === 'ACTIVE' ? true : run.active ?? null,
|
|
76
|
+
impressions: r.impressions ?? null,
|
|
77
|
+
...(platform === 'meta' ? {} : { platforms: [platform] }),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function hostedProvider({ client, apiKey, baseUrl, now = () => Date.now() } = {}) {
|
|
82
|
+
let c = client;
|
|
83
|
+
const http = () => (c ||= (core.hosted?.hostedClient ?? core.hostedClient)({ apiKey, baseUrl }));
|
|
84
|
+
const page = (platform, d, map, fallbackName) => ({
|
|
85
|
+
ads: normalizeAds(platform, (Array.isArray(d.ads) ? d.ads : []).filter((r) => r && typeof r === 'object').map(map), { fallbackName, now: now() }),
|
|
86
|
+
cursor: nextCursor(d),
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
async function meta(args, { status, cursor, fallbackName }) {
|
|
90
|
+
const d = await callTool(http(), HOSTED_TOOLS.meta, withCursor(args, cursor));
|
|
91
|
+
return page('meta', d, (r) => toolRowToAd(r, { platform: 'meta', status, now: now() }), fallbackName);
|
|
92
|
+
}
|
|
93
|
+
async function google(args, { cursor, domain, fallbackName }) {
|
|
94
|
+
const d = await callTool(http(), HOSTED_TOOLS.google, withCursor(args, cursor));
|
|
95
|
+
return page('google', d, (r) => toolRowToAd(r, { platform: 'google', domain, now: now() }), fallbackName);
|
|
96
|
+
}
|
|
97
|
+
async function linkedin(args, { cursor, fallbackName }) {
|
|
98
|
+
const d = await callTool(http(), HOSTED_TOOLS.linkedin, withCursor(args, cursor));
|
|
99
|
+
return page('linkedin', d, (r) => toolRowToAd(r, { platform: 'linkedin', now: now() }), fallbackName);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function companyAds({ platform, pageId, company, domain, country, status, mediaType, cursor, limit }) {
|
|
103
|
+
if (platform === 'meta') {
|
|
104
|
+
const who = pageId ? { pageId } : { companyName: company, domain };
|
|
105
|
+
return meta({ ...who, country, status, mediaType, limit: pageSize(limit) }, { status, cursor, fallbackName: company });
|
|
106
|
+
}
|
|
107
|
+
if (platform === 'google') return google({ domain, advertiserId: pageId, region: country, limit: pageSize(limit) }, { cursor, domain, fallbackName: company });
|
|
108
|
+
if (platform === 'linkedin') return linkedin({ company, companyId: pageId, countries: country, limit: pageSize(limit) }, { cursor, fallbackName: company });
|
|
109
|
+
throw new Error(`Unknown ad platform "${platform}".`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return defineProvider({
|
|
113
|
+
id: 'hosted',
|
|
114
|
+
platforms: ['meta', 'google', 'linkedin'],
|
|
115
|
+
|
|
116
|
+
async searchAds({ platform, query, country, status, mediaType, cursor, limit }) {
|
|
117
|
+
if (platform === 'meta') return meta({ query, country, status, mediaType, limit: pageSize(limit) }, { status, cursor });
|
|
118
|
+
if (platform === 'linkedin') return linkedin({ keyword: query, countries: country, limit: pageSize(limit) }, { cursor });
|
|
119
|
+
if (platform === 'google') return companyAds({ platform, domain: query, country, cursor, limit });
|
|
120
|
+
throw new Error(`Unknown ad platform "${platform}".`);
|
|
121
|
+
},
|
|
122
|
+
|
|
123
|
+
companyAds,
|
|
124
|
+
|
|
125
|
+
async findAdvertisers({ platform, query, domain }) {
|
|
126
|
+
if (platform === 'meta') {
|
|
127
|
+
const d = await callTool(http(), HOSTED_TOOLS.meta, { companyName: query, domain, limit: 1 });
|
|
128
|
+
const a = d.advertiser && typeof d.advertiser === 'object' ? d.advertiser : null;
|
|
129
|
+
if (a?.confirmed === true && a.pageId != null) return { advertisers: [{ id: str(a.pageId), name: str(a.name || query), confirmed: true }] };
|
|
130
|
+
return {
|
|
131
|
+
advertisers: (Array.isArray(a?.candidates) ? a.candidates : [])
|
|
132
|
+
.filter((p) => p && p.pageId != null)
|
|
133
|
+
.map((p) => ({ id: str(p.pageId), name: str(p.name), instagram: p.instagram || null, likes: p.likes ?? null })),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
if (platform === 'google' || platform === 'linkedin') return { advertisers: [] };
|
|
137
|
+
throw new Error(`Unknown ad platform "${platform}".`);
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
|
|
2
|
+
import { defineProvider } from '../provider.js';
|
|
3
|
+
|
|
4
|
+
const has = (hay, needle) => String(hay || '').toLowerCase().includes(String(needle || '').toLowerCase());
|
|
5
|
+
|
|
6
|
+
export function memoryProvider({ ads = {}, advertisers = {}, pageSize = 30 } = {}) {
|
|
7
|
+
const page = (rows, cursor, limit) => {
|
|
8
|
+
const size = Math.max(1, Math.min(pageSize, Number(limit) || pageSize));
|
|
9
|
+
const start = Number(cursor) || 0;
|
|
10
|
+
const slice = rows.slice(start, start + size);
|
|
11
|
+
return { ads: slice, cursor: start + size < rows.length ? String(start + size) : null };
|
|
12
|
+
};
|
|
13
|
+
const textOf = (r) => [r.advertiser, r.headline, r.body].join(' ');
|
|
14
|
+
return defineProvider({
|
|
15
|
+
id: 'memory',
|
|
16
|
+
platforms: Object.keys(ads).length ? Object.keys(ads) : ['meta', 'google', 'linkedin'],
|
|
17
|
+
async searchAds({ platform, query, cursor, limit }) {
|
|
18
|
+
return page((ads[platform] || []).filter((r) => has(textOf(r), query)), cursor, limit);
|
|
19
|
+
},
|
|
20
|
+
async companyAds({ platform, pageId, company, domain, cursor, limit }) {
|
|
21
|
+
const rows = (ads[platform] || []).filter((r) =>
|
|
22
|
+
(pageId && String(r.advertiserId) === String(pageId))
|
|
23
|
+
|| (company && has(r.advertiser, company))
|
|
24
|
+
|| (domain && (has(r.domain, domain) || has(r.link, domain))));
|
|
25
|
+
return page(rows, cursor, limit);
|
|
26
|
+
},
|
|
27
|
+
async findAdvertisers({ platform, query }) {
|
|
28
|
+
return { advertisers: (advertisers[platform] || []).filter((a) => has(a.name, query) || has(a.instagram, query)) };
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
}
|
package/src/research.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
|
|
2
|
+
import * as core from '@hermoso/core';
|
|
3
|
+
import { hooks } from '@hermoso/core';
|
|
4
|
+
|
|
5
|
+
const fetchSafe = (...a) => (core.http?.fetchSafe ?? core.fetchSafe)(...a);
|
|
6
|
+
import { assertPlatform, defineProvider } from './provider.js';
|
|
7
|
+
import { hostedProvider } from './providers/hosted.js';
|
|
8
|
+
import { normalizeAds, normalizeAdvertiser, advertiserIsBrand } from './normalize.js';
|
|
9
|
+
import { dedupeAds } from './dedupe.js';
|
|
10
|
+
import { sortAds } from './longevity.js';
|
|
11
|
+
import { resolvePage, instagramFromHtml } from './resolve-page.js';
|
|
12
|
+
import { findCompetitors, cleanDomain } from './discovery.js';
|
|
13
|
+
import { competitorTeardown, mineAngles } from './teardown.js';
|
|
14
|
+
|
|
15
|
+
async function metered(op, fn) {
|
|
16
|
+
const hold = await hooks.billing.reserve({ op, units: { lookups: 1 }, meta: {} });
|
|
17
|
+
try {
|
|
18
|
+
const out = await fn();
|
|
19
|
+
await hooks.billing.settle(hold?.holdId ?? null, { units: { lookups: 1 } });
|
|
20
|
+
return out;
|
|
21
|
+
} catch (e) {
|
|
22
|
+
await hooks.billing.release(hold?.holdId ?? null);
|
|
23
|
+
throw e;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const defaultFetchPage = async (url) => {
|
|
28
|
+
const r = await fetchSafe(url, { headers: { 'user-agent': 'Mozilla/5.0 (compatible; hermoso-research)' } });
|
|
29
|
+
return r && r.ok ? r.text() : '';
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* createResearch({ provider?, text?, fetchPage? })
|
|
34
|
+
* provider — a research data provider (default: hosted Hermoso)
|
|
35
|
+
* text — a text provider with complete() (default: @hermoso/core providers.text)
|
|
36
|
+
* fetchPage — url -> html, for reading a brand's own site (default: core fetchSafe)
|
|
37
|
+
*/
|
|
38
|
+
export function createResearch({ provider, text, fetchPage = defaultFetchPage } = {}) {
|
|
39
|
+
let p = provider ? defineProvider(provider) : null;
|
|
40
|
+
const data = () => (p ||= hostedProvider());
|
|
41
|
+
|
|
42
|
+
async function searchAds({ platform = 'meta', query, country = 'ALL', status = 'ALL', mediaType, sort = 'longest_running', limit = 30, cursor } = {}) {
|
|
43
|
+
if (!String(query || '').trim()) throw new Error('Give a search query.');
|
|
44
|
+
assertPlatform(data(), platform);
|
|
45
|
+
const page = await metered(`research.search.${platform}`, () => data().searchAds({ platform, query, country, status, mediaType, cursor, limit }));
|
|
46
|
+
const ads = dedupeAds(sortAds(normalizeAds(platform, page.ads, { fallbackName: query }), sort)).slice(0, limit);
|
|
47
|
+
return { platform, query, ads, cursor: page.cursor || null };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function findAdvertisers({ platform = 'meta', query, domain } = {}) {
|
|
51
|
+
if (!String(query || '').trim()) throw new Error('Give a name to search for.');
|
|
52
|
+
assertPlatform(data(), platform);
|
|
53
|
+
const out = await metered(`research.advertisers.${platform}`, () => data().findAdvertisers({ platform, query, ...(domain ? { domain } : {}) }));
|
|
54
|
+
return { advertisers: (Array.isArray(out?.advertisers) ? out.advertisers : []).map(normalizeAdvertiser).filter(Boolean) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Resolve a brand to its Meta page. Confident matches only; a namesake is never returned. */
|
|
58
|
+
async function resolveMetaPage({ name, domain, instagram } = {}) {
|
|
59
|
+
let ig = instagram || '';
|
|
60
|
+
const d = cleanDomain(domain);
|
|
61
|
+
if (!ig && d) { try { ig = instagramFromHtml(await fetchPage(`https://${d}/`)); } catch { ig = ''; } }
|
|
62
|
+
const queries = [...new Set([name, d && d.split('.')[0], ig].filter(Boolean))];
|
|
63
|
+
let best = { page: null, score: 0, confident: false, candidates: [] };
|
|
64
|
+
for (const q of queries.slice(0, 2)) {
|
|
65
|
+
const { advertisers } = await findAdvertisers({ platform: 'meta', query: q, domain: d || undefined });
|
|
66
|
+
const r = resolvePage(advertisers, { name, domain: d, instagram: ig });
|
|
67
|
+
if (r.score > best.score) best = r;
|
|
68
|
+
if (r.confident) break;
|
|
69
|
+
}
|
|
70
|
+
return { ...best, instagram: ig || null };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A brand's own ads, per platform, longest-running first, deduped. */
|
|
74
|
+
async function pullCompetitorAds({ name = '', domain = '', pageId, platforms = ['meta'], country = 'ALL', status = 'ALL', sort = 'longest_running', limit = 12 } = {}) {
|
|
75
|
+
if (!name && !domain && !pageId) throw new Error('Name the brand (or give its domain).');
|
|
76
|
+
const results = {};
|
|
77
|
+
const notes = [];
|
|
78
|
+
for (const platform of platforms) {
|
|
79
|
+
try {
|
|
80
|
+
assertPlatform(data(), platform);
|
|
81
|
+
if (platform === 'meta') {
|
|
82
|
+
let id = pageId;
|
|
83
|
+
if (!id) {
|
|
84
|
+
const r = await resolveMetaPage({ name, domain });
|
|
85
|
+
if (!r.confident) {
|
|
86
|
+
notes.push(`Meta: no page confidently matches ${name || domain}${r.candidates[0] ? ` (closest: ${r.candidates[0].page?.name})` : ''}, so no ads are shown rather than a namesake's. Pass pageId to choose one.`);
|
|
87
|
+
results.meta = [];
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
id = r.page.id;
|
|
91
|
+
}
|
|
92
|
+
const page = await metered('research.company.meta', () => data().companyAds({ platform, pageId: id, country, status }));
|
|
93
|
+
results.meta = dedupeAds(sortAds(normalizeAds('meta', page.ads, { fallbackName: name }), sort)).slice(0, limit);
|
|
94
|
+
} else if (platform === 'google') {
|
|
95
|
+
const d = cleanDomain(domain);
|
|
96
|
+
if (!d) { notes.push('Google: needs the brand\'s domain.'); results.google = []; continue; }
|
|
97
|
+
const page = await metered('research.company.google', () => data().companyAds({ platform, domain: d, country: country === 'ALL' ? undefined : country }));
|
|
98
|
+
results.google = dedupeAds(sortAds(normalizeAds('google', page.ads, { fallbackName: name }), sort)).slice(0, limit);
|
|
99
|
+
} else if (platform === 'linkedin') {
|
|
100
|
+
const page = await metered('research.company.linkedin', () => data().companyAds({ platform, company: name || domain, country: country === 'ALL' ? undefined : country }));
|
|
101
|
+
const all = normalizeAds('linkedin', page.ads);
|
|
102
|
+
const kept = all.filter((a) => advertiserIsBrand(a, name, domain));
|
|
103
|
+
if (all.length && !kept.length) notes.push(`LinkedIn matches on name only, and none of the ${all.length} ads it returned came from ${name || domain}.`);
|
|
104
|
+
results.linkedin = dedupeAds(sortAds(kept, sort)).slice(0, limit);
|
|
105
|
+
}
|
|
106
|
+
} catch (e) {
|
|
107
|
+
notes.push(`${platform}: ${e.message}`);
|
|
108
|
+
results[platform] = null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return { brand: { name, domain: cleanDomain(domain) || null }, ads: results, notes };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
get provider() { return data(); },
|
|
116
|
+
searchAds,
|
|
117
|
+
findAdvertisers,
|
|
118
|
+
resolveMetaPage,
|
|
119
|
+
pullCompetitorAds,
|
|
120
|
+
findCompetitors: (o = {}) => findCompetitors({ text, fetchPage, ...o }),
|
|
121
|
+
competitorTeardown: (o = {}) => competitorTeardown({ text, ...o }),
|
|
122
|
+
mineAngles: (o = {}) => mineAngles({ text, ...o }),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
|
|
2
|
+
export const CONFIDENT = 80;
|
|
3
|
+
|
|
4
|
+
const flat = (s) => String(s || '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '');
|
|
5
|
+
const domainToken = (d) => {
|
|
6
|
+
const host = String(d || '').replace(/^https?:\/\//i, '').replace(/^www\./i, '').split(/[/?#]/)[0];
|
|
7
|
+
const parts = host.split('.');
|
|
8
|
+
return flat(parts.length > 1 ? parts[parts.length - 2] : parts[0]);
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export function scorePage(page, { name = '', domain = '', instagram = '' } = {}) {
|
|
12
|
+
if (!page) return 0;
|
|
13
|
+
const ig = flat(String(instagram).replace(/^@/, ''));
|
|
14
|
+
const pageIg = flat(page.instagram || '');
|
|
15
|
+
if (ig && pageIg && ig === pageIg) return 100;
|
|
16
|
+
if (page.confirmed === true && !(ig && pageIg)) return 95;
|
|
17
|
+
const pn = flat(page.name);
|
|
18
|
+
const want = flat(name);
|
|
19
|
+
const tok = domainToken(domain);
|
|
20
|
+
let s = 0;
|
|
21
|
+
if (want && pn === want) s = 85;
|
|
22
|
+
else if (tok && pn === tok) s = 82;
|
|
23
|
+
else if (want && (pn.includes(want) || want.includes(pn)) && pn.length > 2) s = 55;
|
|
24
|
+
else if (tok && pn.includes(tok) && tok.length > 2) s = 50;
|
|
25
|
+
if (ig && pageIg && ig !== pageIg) s -= 30;
|
|
26
|
+
const likes = Number(page.likes ?? page.followers ?? 0);
|
|
27
|
+
if (s > 0 && likes > 0) s += Math.min(5, Math.log10(likes));
|
|
28
|
+
return Math.max(0, Math.round(s * 10) / 10);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Pick the best candidate. Returns { page, score, confident, candidates } — page is null when nothing is confident. */
|
|
32
|
+
export function resolvePage(candidates, brand) {
|
|
33
|
+
const scored = (Array.isArray(candidates) ? candidates : [])
|
|
34
|
+
.map((p) => ({ page: p, score: scorePage(p, brand) }))
|
|
35
|
+
.sort((a, b) => b.score - a.score);
|
|
36
|
+
const top = scored[0];
|
|
37
|
+
const confident = !!top && top.score >= CONFIDENT;
|
|
38
|
+
return { page: confident ? top.page : null, score: top ? top.score : 0, confident, candidates: scored.slice(0, 5) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Find the Instagram handle a brand's website links to (from its HTML). */
|
|
42
|
+
export function instagramFromHtml(html) {
|
|
43
|
+
const m = String(html || '').match(/instagram\.com\/([A-Za-z0-9_.]{2,30})(?=["'/?#\s])/i);
|
|
44
|
+
if (!m) return '';
|
|
45
|
+
const h = m[1].replace(/\.$/, '');
|
|
46
|
+
return /^(p|reel|reels|explore|accounts|stories|tv)$/i.test(h) ? '' : h;
|
|
47
|
+
}
|
package/src/teardown.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
|
|
2
|
+
import { askJson } from './llm.js';
|
|
3
|
+
|
|
4
|
+
export const HOOK_TYPES = Object.freeze(['problem-agitate', 'social-proof', 'question', 'stat-shock', 'lifestyle-aspiration', 'offer-led', 'curiosity-gap']);
|
|
5
|
+
|
|
6
|
+
export const TEARDOWN_SCHEMA = {
|
|
7
|
+
type: 'object', additionalProperties: false,
|
|
8
|
+
properties: {
|
|
9
|
+
hook_taxonomy: {
|
|
10
|
+
type: 'array', description: 'the opening-hook mix: one entry per hook type that actually appears',
|
|
11
|
+
items: { type: 'object', additionalProperties: false, properties: { type: { type: 'string', enum: [...HOOK_TYPES] }, count: { type: 'integer' }, example: { type: 'string' } }, required: ['type', 'count', 'example'] },
|
|
12
|
+
},
|
|
13
|
+
campaigns: {
|
|
14
|
+
type: 'array', description: 'recurring themes across their longest-running ads',
|
|
15
|
+
items: { type: 'object', additionalProperties: false, properties: { theme: { type: 'string' }, ad_count: { type: 'integer' }, longest_running_days: { type: 'integer' }, landing_angle: { type: 'string' } }, required: ['theme', 'ad_count', 'longest_running_days', 'landing_angle'] },
|
|
16
|
+
},
|
|
17
|
+
white_space: {
|
|
18
|
+
type: 'array', description: '2-4 angles nobody in the set runs',
|
|
19
|
+
items: { type: 'object', additionalProperties: false, properties: { angle: { type: 'string' }, why_open: { type: 'string' } }, required: ['angle', 'why_open'] },
|
|
20
|
+
},
|
|
21
|
+
counter_plays: {
|
|
22
|
+
type: 'array', description: '2-3 ready-to-make ad briefs that exploit a weakness in the set',
|
|
23
|
+
items: { type: 'object', additionalProperties: false, properties: { title: { type: 'string' }, brief: { type: 'string' }, format: { type: 'string', enum: ['image', 'video'] } }, required: ['title', 'brief', 'format'] },
|
|
24
|
+
},
|
|
25
|
+
not_saying: { type: 'array', description: '3-6 claims or territories to avoid because the competitor owns them', items: { type: 'string' } },
|
|
26
|
+
},
|
|
27
|
+
required: ['hook_taxonomy', 'campaigns', 'white_space', 'counter_plays', 'not_saying'],
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const TEARDOWN_SYSTEM = `You are a senior competitive ad strategist. You are given ONE competitor's REAL ads (advertiser, opening copy, CTA, run length, format). Reverse-engineer their playbook and turn it into moves THIS brand can act on:
|
|
31
|
+
- hook_taxonomy: classify each ad's opening into the 7-type taxonomy (problem-agitate, social-proof, question, stat-shock, lifestyle-aspiration, offer-led, curiosity-gap); report only the types that appear, each with a count and a short real example.
|
|
32
|
+
- campaigns: cluster the ads into recurring themes. The longest-running ones are proven winners: give their run length and the offer or positioning they land on.
|
|
33
|
+
- white_space: 2-4 angles nobody in their set runs.
|
|
34
|
+
- counter_plays: 2-3 concrete ad briefs (hook + angle + what to show) that exploit a specific weakness you see.
|
|
35
|
+
- not_saying: 3-6 specific phrases, claims or territories this brand should avoid because the competitor owns them.
|
|
36
|
+
Ground everything in the actual ads. Never invent stats, offers or claims that are not evidenced. When the brand is provided, tailor white space and counter-plays to it.`;
|
|
37
|
+
|
|
38
|
+
export const ANGLES_SCHEMA = {
|
|
39
|
+
type: 'object', additionalProperties: false,
|
|
40
|
+
properties: {
|
|
41
|
+
angles: {
|
|
42
|
+
type: 'array',
|
|
43
|
+
items: {
|
|
44
|
+
type: 'object', additionalProperties: false,
|
|
45
|
+
properties: { name: { type: 'string' }, hook: { type: 'string' }, why: { type: 'string' }, evidence: { type: 'string' }, format: { type: 'string', enum: ['image', 'video', 'carousel', 'any'] } },
|
|
46
|
+
required: ['name', 'hook', 'why', 'evidence', 'format'],
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
required: ['angles'],
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export const ANGLES_SYSTEM = `You mine advertising angles from real ads. An angle is the reason someone should care (a problem, desire, objection, identity or moment), not a format. Return 5-10 distinct angles that the given brand could run, each with a sample opening hook (max 12 words), why it works, which ads evidence it (advertiser + a few words), and the best format. Never invent proof points.`;
|
|
54
|
+
|
|
55
|
+
const clip = (s, n) => String(s ?? '').replace(/\s+/g, ' ').trim().slice(0, n);
|
|
56
|
+
|
|
57
|
+
/** One compact line per normalized ad, for a prompt. */
|
|
58
|
+
export function adLine(a, i) {
|
|
59
|
+
return `${i + 1}. [${a.platform}${a.format ? ' ' + a.format : ''}${a.runDays != null ? `, ${a.runDays}d` : ''}${a.active === false ? ', ended' : ''}] ${clip(a.advertiser, 60)}: ${clip([a.headline, a.body].filter(Boolean).join(' / '), 300)}${a.cta ? ` (CTA: ${clip(a.cta, 30)})` : ''}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const brandLine = (brand) => (brand && typeof brand === 'object'
|
|
63
|
+
? `The brand: ${clip(brand.name, 80)}${brand.domain ? ` (${brand.domain})` : ''}. ${clip(brand.description || brand.oneLiner, 400)}`
|
|
64
|
+
: '');
|
|
65
|
+
|
|
66
|
+
export async function competitorTeardown({ competitor, ads, brand, language = '', text } = {}) {
|
|
67
|
+
const name = clip(competitor?.name || competitor, 120);
|
|
68
|
+
if (!name) throw new Error('Name the competitor to tear down.');
|
|
69
|
+
const use = (Array.isArray(ads) ? ads : []).filter((a) => a && (a.body || a.headline)).slice(0, 30);
|
|
70
|
+
if (!use.length) throw new Error(`No ads with copy to analyse for ${name}. Pull their ads first (pull_competitor_ads).`);
|
|
71
|
+
const user = [
|
|
72
|
+
`Competitor: ${name}${competitor?.domain ? ` (${competitor.domain})` : ''}`,
|
|
73
|
+
brandLine(brand),
|
|
74
|
+
`Their ads, longest running first:\n${use.map(adLine).join('\n')}`,
|
|
75
|
+
language && `Write in ${language}.`,
|
|
76
|
+
].filter(Boolean).join('\n\n');
|
|
77
|
+
const json = await askJson({ system: TEARDOWN_SYSTEM, user, schema: TEARDOWN_SCHEMA, op: 'research.teardown', text });
|
|
78
|
+
return { competitor: name, adsAnalysed: use.length, ...json };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function mineAngles({ ads, brand, text } = {}) {
|
|
82
|
+
const use = (Array.isArray(ads) ? ads : []).filter((a) => a && (a.body || a.headline)).slice(0, 40);
|
|
83
|
+
if (!use.length) throw new Error('No ads with copy to mine. Search an ad library first.');
|
|
84
|
+
const user = [brandLine(brand), `Ads:\n${use.map(adLine).join('\n')}`].filter(Boolean).join('\n\n');
|
|
85
|
+
return askJson({ system: ANGLES_SYSTEM, user, schema: ANGLES_SCHEMA, op: 'research.angles', text });
|
|
86
|
+
}
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
|
|
2
|
+
import { createResearch } from './research.js';
|
|
3
|
+
import { adLine } from './teardown.js';
|
|
4
|
+
|
|
5
|
+
const PLATFORM = { type: 'string', enum: ['meta', 'google', 'linkedin'], description: 'Which ad library: meta (Facebook, Instagram, Messenger, Threads), google, or linkedin.' };
|
|
6
|
+
const SORT = { type: 'string', enum: ['longest_running', 'newest', 'impressions'], description: 'Longest running first surfaces proven winners (an advertiser keeps paying for what works).' };
|
|
7
|
+
const COUNTRY = { type: 'string', description: 'Two-letter country code, or ALL.' };
|
|
8
|
+
const READ = { readOnlyHint: true, openWorldHint: true };
|
|
9
|
+
|
|
10
|
+
const adsSummary = (ads) => (ads?.length ? ads.slice(0, 12).map(adLine).join('\n') + (ads.length > 12 ? `\n…and ${ads.length - 12} more` : '') : 'No ads.');
|
|
11
|
+
|
|
12
|
+
export function createResearchTools(opts = {}) {
|
|
13
|
+
const r = opts.research || createResearch(opts);
|
|
14
|
+
const brandOf = (ctx) => ctx?.brand || null;
|
|
15
|
+
return [
|
|
16
|
+
{
|
|
17
|
+
name: 'find_competitors',
|
|
18
|
+
group: 'research',
|
|
19
|
+
core: true,
|
|
20
|
+
description: 'Find the brands whose ads are worth studying for a company. mode "competitors" returns head-to-head rivals and similar brands; mode "inspiration" returns the most copyable creative from anyone relevant, including non-competitors known for great ads. Give a domain, or a description when there is no website.',
|
|
21
|
+
inputSchema: { type: 'object', properties: { domain: { type: 'string' }, description: { type: 'string' }, mode: { type: 'string', enum: ['competitors', 'inspiration'] }, limit: { type: 'integer' } }, additionalProperties: false },
|
|
22
|
+
annotations: READ,
|
|
23
|
+
run: (a, ctx) => r.findCompetitors({ domain: a.domain || brandOf(ctx)?.domain, description: a.description || (!a.domain ? brandOf(ctx)?.description : ''), mode: a.mode || 'competitors', limit: a.limit || 12 }),
|
|
24
|
+
summarize: (out) => `${out.company || 'Company'} (${out.mode}):\n` + out.candidates.map((c) => `- ${c.name} (${c.domain}) [${c.kind}] ${c.reason}`).join('\n'),
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
name: 'search_ad_library',
|
|
28
|
+
group: 'research',
|
|
29
|
+
core: true,
|
|
30
|
+
description: 'Search a public ad library by keyword (meta, linkedin) or by advertiser domain (google). Returns real ads with copy, media, dates and how long each has run.',
|
|
31
|
+
inputSchema: { type: 'object', properties: { platform: PLATFORM, query: { type: 'string' }, country: COUNTRY, status: { type: 'string', enum: ['ACTIVE', 'INACTIVE', 'ALL'] }, mediaType: { type: 'string', enum: ['ALL', 'IMAGE', 'VIDEO', 'MEME'] }, sort: SORT, limit: { type: 'integer' }, cursor: { type: 'string' } }, required: ['query'], additionalProperties: false },
|
|
32
|
+
annotations: READ,
|
|
33
|
+
run: (a) => r.searchAds({ platform: a.platform || 'meta', ...a }),
|
|
34
|
+
summarize: (out) => `${out.ads.length} ${out.platform} ads for "${out.query}":\n${adsSummary(out.ads)}`,
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'find_advertiser',
|
|
38
|
+
group: 'research',
|
|
39
|
+
description: 'Look up an advertiser in an ad library by name, to get its page or advertiser id.',
|
|
40
|
+
inputSchema: { type: 'object', properties: { platform: PLATFORM, query: { type: 'string' } }, required: ['query'], additionalProperties: false },
|
|
41
|
+
annotations: READ,
|
|
42
|
+
run: (a) => r.findAdvertisers({ platform: a.platform || 'meta', query: a.query }),
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
name: 'pull_competitor_ads',
|
|
46
|
+
group: 'research',
|
|
47
|
+
core: true,
|
|
48
|
+
description: 'Pull one brand\'s own ads, longest running first, deduplicated. On Meta the brand is matched to its page using the Instagram handle its own website links to; an uncertain match returns no ads and a note rather than a namesake\'s ads (pass pageId to choose).',
|
|
49
|
+
inputSchema: { type: 'object', properties: { name: { type: 'string' }, domain: { type: 'string' }, pageId: { type: 'string' }, platforms: { type: 'array', items: PLATFORM }, country: COUNTRY, status: { type: 'string', enum: ['ACTIVE', 'INACTIVE', 'ALL'] }, sort: SORT, limit: { type: 'integer' } }, additionalProperties: false },
|
|
50
|
+
annotations: READ,
|
|
51
|
+
run: (a) => r.pullCompetitorAds(a),
|
|
52
|
+
summarize: (out) => [
|
|
53
|
+
...Object.entries(out.ads).map(([p, ads]) => `${p}: ${ads == null ? 'could not be read' : `${ads.length} ads`}\n${ads ? adsSummary(ads) : ''}`),
|
|
54
|
+
...out.notes,
|
|
55
|
+
].join('\n'),
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: 'competitor_teardown',
|
|
59
|
+
group: 'research',
|
|
60
|
+
description: 'Tear down one competitor\'s ads: their hook mix, proven campaign themes, open angles nobody runs, ready-to-make counter-play briefs, and what to avoid saying. Pulls their Meta ads first unless ads are given.',
|
|
61
|
+
inputSchema: { type: 'object', properties: { name: { type: 'string' }, domain: { type: 'string' }, pageId: { type: 'string' }, ads: { type: 'array', items: { type: 'object' } }, language: { type: 'string' } }, required: ['name'], additionalProperties: false },
|
|
62
|
+
annotations: READ,
|
|
63
|
+
run: async (a, ctx) => {
|
|
64
|
+
let ads = a.ads;
|
|
65
|
+
if (!Array.isArray(ads) || !ads.length) {
|
|
66
|
+
const pulled = await r.pullCompetitorAds({ name: a.name, domain: a.domain, pageId: a.pageId, platforms: ['meta'], limit: 30 });
|
|
67
|
+
ads = pulled.ads.meta || [];
|
|
68
|
+
if (!ads.length) return { competitor: a.name, adsAnalysed: 0, notes: pulled.notes.length ? pulled.notes : [`No ads found for ${a.name}.`] };
|
|
69
|
+
}
|
|
70
|
+
return r.competitorTeardown({ competitor: { name: a.name, domain: a.domain }, ads, brand: brandOf(ctx), language: a.language });
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: 'mine_angles',
|
|
75
|
+
group: 'research',
|
|
76
|
+
description: 'Mine advertising angles (problems, desires, objections, moments) from a set of ads, each with a sample hook and the ads that evidence it. Searches the Meta library for the query when no ads are given.',
|
|
77
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' }, ads: { type: 'array', items: { type: 'object' } } }, additionalProperties: false },
|
|
78
|
+
annotations: READ,
|
|
79
|
+
run: async (a, ctx) => {
|
|
80
|
+
let ads = a.ads;
|
|
81
|
+
if (!Array.isArray(ads) || !ads.length) {
|
|
82
|
+
if (!a.query) throw new Error('Give ads or a query to search for.');
|
|
83
|
+
ads = (await r.searchAds({ platform: 'meta', query: a.query, limit: 30 })).ads;
|
|
84
|
+
}
|
|
85
|
+
return r.mineAngles({ ads, brand: brandOf(ctx) });
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
];
|
|
89
|
+
}
|