@kgma/linkdevi-tools 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 +21 -0
- package/README.md +98 -2
- package/dist/campaign.d.ts +101 -0
- package/dist/campaign.js +162 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +123 -0
- package/dist/index.d.ts +82 -0
- package/dist/index.js +72 -0
- package/examples/campaign.json +12 -0
- package/examples/links.csv +2 -0
- package/examples/sdk-example.ts +13 -0
- package/package.json +59 -4
- package/workflows/01-google-sheets-to-links.json +211 -0
- package/workflows/02-campaign-to-csv.json +164 -0
- package/workflows/03-rss-to-share-kit.json +242 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 LinkDevi contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# LinkDevi developer pack
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Offline Campaign Launch Kit helpers, a TypeScript SDK, a Node.js CLI and three n8n workflows. MIT licensed. Node.js 22+.
|
|
4
|
+
|
|
5
|
+
Package name: `@kgma/linkdevi-tools`. The separately distributed `@kgma/linkdevi-mcp` is the MCP connector. This repository includes the complete source and build instructions; npm releases and source releases carry their own version.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @kgma/linkdevi-tools@0.1.0
|
|
9
|
+
npx --no-install linkdevi --help
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Source: [kgma-glitch/linkdevi-tools](https://github.com/kgma-glitch/linkdevi-tools). Use the source or local tarball instructions below when working before a registry release is available.
|
|
13
|
+
|
|
14
|
+
## Start without an account
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npm ci
|
|
18
|
+
npm run build
|
|
19
|
+
node dist/cli.js campaign init --out campaign.json
|
|
20
|
+
node dist/cli.js campaign preview campaign.json
|
|
21
|
+
node dist/cli.js campaign preview campaign.json --format csv > launch.csv
|
|
22
|
+
node dist/cli.js links import examples/links.csv --dry-run
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Preview, UTM generation, CSV export and CSV preflight run locally, without a key, network request or model. The CSV import command is deliberately a **dry run only**; it does not create links. It accepts at most 100 rows and a 256 KiB file, with columns `url,name,utmCampaign,channels` and optional `domain,requestId`. Separate channels using `|`. CSV exports label destinations as `preview_only`, retain non-UTM query values and fragments, replace old UTM values, and neutralize spreadsheet formulas in text cells.
|
|
26
|
+
|
|
27
|
+
The public website uses the same channel/UTM helpers at `/tools/campaign-launch-kit` and `/th/campaign-launch-kit` (also Chinese, Spanish, Indonesian and Japanese). Preview does not reserve quota. A domain in an offline preview does not prove that the account can use it; the service validates that when saving.
|
|
28
|
+
|
|
29
|
+
## Create and manage saved campaigns
|
|
30
|
+
|
|
31
|
+
1. Create a [LinkDevi account](https://linkdevi.com/register), open Connect AI, and create a scoped key. Use `links:read` and `links:write` for campaign creation, or only `links:read` for read-only use.
|
|
32
|
+
2. Supply `LINKDEVI_API_KEY` through your shell's protected environment or secret manager. The optional `LINKDEVI_BASE_URL` defaults to `https://linkdevi.com`; only HTTPS origins are accepted except localhost HTTP for development.
|
|
33
|
+
3. Edit the generated `campaign.json`, inspect the preview, then deliberately create:
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
node dist/cli.js capabilities
|
|
37
|
+
node dist/cli.js campaign create campaign.json --confirm
|
|
38
|
+
node dist/cli.js campaign list --page 1
|
|
39
|
+
node dist/cli.js campaign stats CAMPAIGN_ID
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`campaign init --out` refuses to overwrite an existing file. Keep the UUID `requestId` and exact payload in that file. A timeout or invalid response may mean creation committed. Retry **only with the original identity and unchanged payload**; do not re-run init to retry. Changed payloads using the same UUID conflict. There are no automatic retries. HTTP 429 retains its numeric `Retry-After` in SDK/CLI errors. Wait before retrying. Never put a real key in arguments, a repository, an issue or a prompt.
|
|
43
|
+
|
|
44
|
+
Each selected channel uses one stored-link slot. Hosted LinkDevi account limits, shared workspace RPM and permissions apply. The package does not include a shortening backend, model subscription or hosted OAuth MCP endpoint. It does not invoke an LLM. For printed QR codes, save the short link first and render that saved link's QR, so its destination can later be edited in the account.
|
|
45
|
+
|
|
46
|
+
## TypeScript SDK
|
|
47
|
+
|
|
48
|
+
Build the source, then import from `./dist/index.js` (the package root exports the same API after local installation). See `examples/sdk-example.ts` for a typed, opt-in example.
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
import { LinkDeviClient, previewCampaign, type CampaignRequest } from './dist/index.js';
|
|
52
|
+
|
|
53
|
+
const intent: CampaignRequest = {
|
|
54
|
+
requestId: 'a43c37c0-350a-44ef-9d40-a5900c246891',
|
|
55
|
+
name: 'December launch', url: 'https://example.com/sale',
|
|
56
|
+
utmCampaign: 'december-launch', domain: 'linkdevi.com',
|
|
57
|
+
channels: ['facebook', 'line', 'print'],
|
|
58
|
+
};
|
|
59
|
+
console.log(previewCampaign(intent)); // local, no quota
|
|
60
|
+
|
|
61
|
+
// Call deliberately after review; store this intent before sending it.
|
|
62
|
+
const client = new LinkDeviClient({ apiKey: process.env.LINKDEVI_API_KEY! });
|
|
63
|
+
const saved = await client.createCampaign(intent);
|
|
64
|
+
console.log(saved.campaign.id);
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The client exposes `capabilities`, `previewCampaign` (authenticated service preview), `createCampaign`, `listCampaigns`, `campaignStats`, and `linkQr`. The root `previewCampaign` helper is the offline alternative. SDK credentials belong in a server, local process, or protected client environment, not a publicly shipped browser bundle. Redirects are rejected and raw network failures are not printed.
|
|
68
|
+
|
|
69
|
+
Reports are best-effort lifetime redirect counters including bots/previews. They do not measure unique people, dated activity, conversions or revenue. A missing channel is unavailable. `linkQr` renders a PNG for an existing saved link and does not persist a separate QR record.
|
|
70
|
+
|
|
71
|
+
## n8n workflow pack
|
|
72
|
+
|
|
73
|
+
Import the JSON files under `workflows/`. They use built-in nodes, are inactive, and start with a manual trigger. Read each workflow's sticky note before running.
|
|
74
|
+
|
|
75
|
+
| File | Input and output |
|
|
76
|
+
| --- | --- |
|
|
77
|
+
| `01-google-sheets-to-links.json` | Read campaign rows, create saved campaigns, update the same sheet by its unique pre-saved `requestId` |
|
|
78
|
+
| `02-campaign-to-csv.json` | Campaign brief → saved campaign links → downloadable CSV |
|
|
79
|
+
| `03-rss-to-share-kit.json` | Up to five RSS articles → deterministic identities → saved share kits → CSV; no social posting |
|
|
80
|
+
|
|
81
|
+
Configure Header Auth in the HTTP node: name `Authorization`, value `Bearer YOUR_SCOPED_KEY`. Select the credential inside n8n; the exported workflow contains no key. Google Sheets also needs your own Google credential and spreadsheet ID in both Sheets nodes. Create columns `requestId,name,url,utmCampaign,channels,domain,shortUrls,campaignId`; save a unique UUID in every source row before running. Completed rows with `shortUrls` are skipped. Use `RAW` when writing values.
|
|
82
|
+
|
|
83
|
+
If you do not have n8n connected to Google yet, import the workflow first and leave it inactive. In each Google Sheets node, select **Create new credential**, complete n8n's Google OAuth setup for your hosting option, and authorize your Google account yourself. Select the same credential and a dedicated test spreadsheet in both nodes. Start with one test campaign row, manually execute, and verify that `shortUrls` and `campaignId` are written back to that row. Execute again to check that the completed row is skipped. Do not enable a schedule before this check. The fixture tests do not verify your Google account or permissions. Follow the [official Google Sheets credential guide](https://docs.n8n.io/integrations/builtin/credentials/google/).
|
|
84
|
+
|
|
85
|
+
For RSS, set the actual feed URL and a stable, unique feed namespace in Prepare article identities. Keep the namespace, article content and campaign fields unchanged on retry. Edited payloads for the same article identity conflict and need review. Replays still consume API requests. HTTP nodes disable redirects and retries and pace batches at 2.5 seconds per item; shared limits can still return 429 and stop execution. These are creation workflows, not offline previews. They send data to LinkDevi only when manually run with configured credentials. They do not schedule, post or send messages.
|
|
86
|
+
|
|
87
|
+
Reference: [n8n HTTP Request](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.httprequest/), [Google Sheets](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.googlesheets/sheet-operations/).
|
|
88
|
+
|
|
89
|
+
## Local installation and verification
|
|
90
|
+
|
|
91
|
+
```sh
|
|
92
|
+
npm test
|
|
93
|
+
npm pack
|
|
94
|
+
# In another project, install the generated local artifact:
|
|
95
|
+
npm install /absolute/path/to/kgma-linkdevi-tools-0.1.0.tgz
|
|
96
|
+
npx --no-install linkdevi --help
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
The package includes compiled JavaScript, TypeScript declarations, examples, workflows, README and license. Tests, local environments, npm credentials and infrastructure are excluded. Source tests exercise URL semantics, CSV injection/quoting/bounds, retry identity, transport restrictions and CLI behavior. Real account/provider checks must be distinguished from fixture tests; no real demand or conversion outcome is inferred from passing tests.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Offline-only helpers. No network, credentials, storage or model provider. */
|
|
2
|
+
export declare const campaignChannels: {
|
|
3
|
+
readonly facebook: {
|
|
4
|
+
readonly source: "facebook";
|
|
5
|
+
readonly medium: "social";
|
|
6
|
+
readonly label: "Facebook";
|
|
7
|
+
};
|
|
8
|
+
readonly instagram: {
|
|
9
|
+
readonly source: "instagram";
|
|
10
|
+
readonly medium: "social";
|
|
11
|
+
readonly label: "Instagram";
|
|
12
|
+
};
|
|
13
|
+
readonly tiktok: {
|
|
14
|
+
readonly source: "tiktok";
|
|
15
|
+
readonly medium: "social";
|
|
16
|
+
readonly label: "TikTok";
|
|
17
|
+
};
|
|
18
|
+
readonly line: {
|
|
19
|
+
readonly source: "line";
|
|
20
|
+
readonly medium: "messaging";
|
|
21
|
+
readonly label: "LINE";
|
|
22
|
+
};
|
|
23
|
+
readonly email: {
|
|
24
|
+
readonly source: "newsletter";
|
|
25
|
+
readonly medium: "email";
|
|
26
|
+
readonly label: "Email";
|
|
27
|
+
};
|
|
28
|
+
readonly print: {
|
|
29
|
+
readonly source: "qr";
|
|
30
|
+
readonly medium: "offline";
|
|
31
|
+
readonly label: "QR / Print";
|
|
32
|
+
};
|
|
33
|
+
readonly youtube: {
|
|
34
|
+
readonly source: "youtube";
|
|
35
|
+
readonly medium: "video";
|
|
36
|
+
readonly label: "YouTube";
|
|
37
|
+
};
|
|
38
|
+
readonly x: {
|
|
39
|
+
readonly source: "x";
|
|
40
|
+
readonly medium: "social";
|
|
41
|
+
readonly label: "X";
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
export type CampaignChannel = keyof typeof campaignChannels;
|
|
45
|
+
export declare const channelKeys: CampaignChannel[];
|
|
46
|
+
export interface CampaignDraft {
|
|
47
|
+
name: string;
|
|
48
|
+
url: string;
|
|
49
|
+
utmCampaign: string;
|
|
50
|
+
domain: string;
|
|
51
|
+
channels: CampaignChannel[];
|
|
52
|
+
}
|
|
53
|
+
export interface CampaignRequest extends CampaignDraft {
|
|
54
|
+
requestId: string;
|
|
55
|
+
}
|
|
56
|
+
export declare const isRequestId: (value: unknown) => value is string;
|
|
57
|
+
export declare function normalizeUrl(value: string): string;
|
|
58
|
+
export declare function campaignSlug(name: string): string;
|
|
59
|
+
export declare function campaignDestination(url: string, campaign: string, channel: CampaignChannel): string;
|
|
60
|
+
export declare function validateCampaign(value: unknown, requireIdentity?: boolean): CampaignDraft & {
|
|
61
|
+
requestId?: string;
|
|
62
|
+
};
|
|
63
|
+
export declare function previewCampaign(value: unknown): {
|
|
64
|
+
linksToCreate: number;
|
|
65
|
+
channels: {
|
|
66
|
+
channel: "facebook" | "instagram" | "tiktok" | "line" | "email" | "youtube" | "x" | "print";
|
|
67
|
+
destinationUrl: string;
|
|
68
|
+
}[];
|
|
69
|
+
createsResources: false;
|
|
70
|
+
requestId?: string | undefined;
|
|
71
|
+
};
|
|
72
|
+
export declare function csvCell(value: unknown): string;
|
|
73
|
+
export declare function launchCsv(value: unknown): string;
|
|
74
|
+
export declare function parseCsv(raw: string): string[][];
|
|
75
|
+
export declare function planCsvImport(raw: string): {
|
|
76
|
+
dryRun: true;
|
|
77
|
+
createsResources: false;
|
|
78
|
+
rows: ({
|
|
79
|
+
row: number;
|
|
80
|
+
valid: true;
|
|
81
|
+
campaign: CampaignDraft & {
|
|
82
|
+
requestId?: string;
|
|
83
|
+
};
|
|
84
|
+
preview: {
|
|
85
|
+
linksToCreate: number;
|
|
86
|
+
channels: {
|
|
87
|
+
channel: "facebook" | "instagram" | "tiktok" | "line" | "email" | "youtube" | "x" | "print";
|
|
88
|
+
destinationUrl: string;
|
|
89
|
+
}[];
|
|
90
|
+
createsResources: false;
|
|
91
|
+
requestId?: string | undefined;
|
|
92
|
+
};
|
|
93
|
+
error?: undefined;
|
|
94
|
+
} | {
|
|
95
|
+
row: number;
|
|
96
|
+
valid: false;
|
|
97
|
+
error: string;
|
|
98
|
+
campaign?: undefined;
|
|
99
|
+
preview?: undefined;
|
|
100
|
+
})[];
|
|
101
|
+
};
|
package/dist/campaign.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/** Offline-only helpers. No network, credentials, storage or model provider. */
|
|
2
|
+
export const campaignChannels = {
|
|
3
|
+
facebook: { source: "facebook", medium: "social", label: "Facebook" },
|
|
4
|
+
instagram: { source: "instagram", medium: "social", label: "Instagram" },
|
|
5
|
+
tiktok: { source: "tiktok", medium: "social", label: "TikTok" },
|
|
6
|
+
line: { source: "line", medium: "messaging", label: "LINE" },
|
|
7
|
+
email: { source: "newsletter", medium: "email", label: "Email" },
|
|
8
|
+
print: { source: "qr", medium: "offline", label: "QR / Print" },
|
|
9
|
+
youtube: { source: "youtube", medium: "video", label: "YouTube" },
|
|
10
|
+
x: { source: "x", medium: "social", label: "X" },
|
|
11
|
+
};
|
|
12
|
+
export const channelKeys = Object.keys(campaignChannels);
|
|
13
|
+
export const isRequestId = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
14
|
+
export function normalizeUrl(value) {
|
|
15
|
+
const text = value.trim();
|
|
16
|
+
if (!text || text.length > 2048)
|
|
17
|
+
throw new Error("Enter a URL up to 2,048 characters.");
|
|
18
|
+
if (text.includes("://") && !/^https?:\/\//i.test(text))
|
|
19
|
+
throw new Error("Use an http or https URL.");
|
|
20
|
+
const url = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`);
|
|
21
|
+
if (!["http:", "https:"].includes(url.protocol) || !url.hostname || url.username || url.password || url.href.length > 2048)
|
|
22
|
+
throw new Error("Enter a valid http or https URL.");
|
|
23
|
+
return url.href;
|
|
24
|
+
}
|
|
25
|
+
export function campaignSlug(name) {
|
|
26
|
+
return name.normalize("NFKC").toLowerCase().trim().replace(/[^\p{L}\p{M}\p{N}._-]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 100);
|
|
27
|
+
}
|
|
28
|
+
export function campaignDestination(url, campaign, channel) {
|
|
29
|
+
const destination = new URL(url);
|
|
30
|
+
for (const key of [...destination.searchParams.keys()])
|
|
31
|
+
if (/^utm_/i.test(key))
|
|
32
|
+
destination.searchParams.delete(key);
|
|
33
|
+
destination.searchParams.set("utm_source", campaignChannels[channel].source);
|
|
34
|
+
destination.searchParams.set("utm_medium", campaignChannels[channel].medium);
|
|
35
|
+
destination.searchParams.set("utm_campaign", campaign);
|
|
36
|
+
return destination.href;
|
|
37
|
+
}
|
|
38
|
+
function text(value, field) {
|
|
39
|
+
if (typeof value !== "string" || !value.trim() || value.trim().length > 100 || /[\u0000-\u001f\u007f]/.test(value))
|
|
40
|
+
throw new Error(`Invalid ${field}`);
|
|
41
|
+
return value.trim();
|
|
42
|
+
}
|
|
43
|
+
export function validateCampaign(value, requireIdentity = false) {
|
|
44
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
45
|
+
throw new Error("Invalid campaign");
|
|
46
|
+
const input = value;
|
|
47
|
+
if (Object.keys(input).some(key => !["requestId", "name", "url", "utmCampaign", "domain", "channels"].includes(key)))
|
|
48
|
+
throw new Error("Unknown campaign field");
|
|
49
|
+
const name = text(input.name, "name"), utmCampaign = text(input.utmCampaign, "utmCampaign");
|
|
50
|
+
if (typeof input.url !== "string")
|
|
51
|
+
throw new Error("Invalid URL");
|
|
52
|
+
const url = normalizeUrl(input.url);
|
|
53
|
+
const domain = input.domain ?? "linkdevi.com";
|
|
54
|
+
// Public preview never claims that a domain is available to the account.
|
|
55
|
+
if (typeof domain !== "string" || domain.length > 253 || !/^[a-z0-9]+(?:[.-][a-z0-9]+)*\.[a-z]{2,}$/i.test(domain))
|
|
56
|
+
throw new Error("Invalid domain");
|
|
57
|
+
if (!Array.isArray(input.channels) || input.channels.length < 1 || input.channels.length > 8 || new Set(input.channels).size !== input.channels.length || input.channels.some(key => !channelKeys.includes(key)))
|
|
58
|
+
throw new Error("Select 1–8 distinct supported channels");
|
|
59
|
+
const channels = input.channels;
|
|
60
|
+
if (channels.some(key => campaignDestination(url, utmCampaign, key).length > 2048))
|
|
61
|
+
throw new Error("Tagged URL exceeds 2048 characters");
|
|
62
|
+
if ((requireIdentity || input.requestId !== undefined) && !isRequestId(input.requestId))
|
|
63
|
+
throw new Error("Provide a stable UUID requestId; preserve it and the exact payload on retry");
|
|
64
|
+
return { name, url, utmCampaign, domain, channels: [...channels], ...(input.requestId ? { requestId: String(input.requestId).toLowerCase() } : {}) };
|
|
65
|
+
}
|
|
66
|
+
export function previewCampaign(value) {
|
|
67
|
+
const draft = validateCampaign(value);
|
|
68
|
+
return {
|
|
69
|
+
...(draft.requestId ? { requestId: draft.requestId } : {}),
|
|
70
|
+
linksToCreate: draft.channels.length,
|
|
71
|
+
channels: draft.channels.map(channel => ({ channel, destinationUrl: campaignDestination(draft.url, draft.utmCampaign, channel) })),
|
|
72
|
+
createsResources: false,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export function csvCell(value) {
|
|
76
|
+
let text = String(value ?? "");
|
|
77
|
+
if (/^[\s\u0000-\u001f]*[=+@-]/.test(text))
|
|
78
|
+
text = "'" + text;
|
|
79
|
+
return '"' + text.replaceAll('"', '""') + '"';
|
|
80
|
+
}
|
|
81
|
+
export function launchCsv(value) {
|
|
82
|
+
const draft = validateCampaign(value), preview = previewCampaign(draft);
|
|
83
|
+
return "\uFEFF" + [
|
|
84
|
+
["campaign", "channel", "utm_source", "utm_medium", "utm_campaign", "destination_url", "status"],
|
|
85
|
+
...preview.channels.map(row => [draft.name, row.channel, campaignChannels[row.channel].source, campaignChannels[row.channel].medium, draft.utmCampaign, row.destinationUrl, "preview_only"]),
|
|
86
|
+
].map(row => row.map(csvCell).join(",")).join("\r\n");
|
|
87
|
+
}
|
|
88
|
+
export function parseCsv(raw) {
|
|
89
|
+
if (new TextEncoder().encode(raw).byteLength > 262144)
|
|
90
|
+
throw new Error("CSV exceeds 256 KiB");
|
|
91
|
+
const input = raw.replace(/^\uFEFF/, ""), rows = [];
|
|
92
|
+
let row = [], cell = "", quoted = false, closed = false;
|
|
93
|
+
const flushCell = () => { row.push(cell); cell = ""; closed = false; };
|
|
94
|
+
const flushRow = () => { flushCell(); if (row.some(Boolean))
|
|
95
|
+
rows.push(row); row = []; if (rows.length > 101)
|
|
96
|
+
throw new Error("Maximum 100 data rows"); };
|
|
97
|
+
for (let i = 0; i < input.length; i++) {
|
|
98
|
+
const ch = input[i];
|
|
99
|
+
if (quoted) {
|
|
100
|
+
if (ch === '"' && input[i + 1] === '"') {
|
|
101
|
+
cell += '"';
|
|
102
|
+
i++;
|
|
103
|
+
}
|
|
104
|
+
else if (ch === '"') {
|
|
105
|
+
quoted = false;
|
|
106
|
+
closed = true;
|
|
107
|
+
}
|
|
108
|
+
else
|
|
109
|
+
cell += ch;
|
|
110
|
+
}
|
|
111
|
+
else if (ch === '"') {
|
|
112
|
+
if (cell || closed)
|
|
113
|
+
throw new Error("Invalid CSV quoting");
|
|
114
|
+
quoted = true;
|
|
115
|
+
}
|
|
116
|
+
else if (ch === ",")
|
|
117
|
+
flushCell();
|
|
118
|
+
else if (ch === "\n" || ch === "\r") {
|
|
119
|
+
if (ch === "\r" && input[i + 1] === "\n")
|
|
120
|
+
i++;
|
|
121
|
+
flushRow();
|
|
122
|
+
}
|
|
123
|
+
else {
|
|
124
|
+
if (closed)
|
|
125
|
+
throw new Error("Unexpected character after CSV quote");
|
|
126
|
+
cell += ch;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (quoted)
|
|
130
|
+
throw new Error("Unclosed CSV quote");
|
|
131
|
+
if (cell || row.length || closed)
|
|
132
|
+
flushRow();
|
|
133
|
+
return rows;
|
|
134
|
+
}
|
|
135
|
+
export function planCsvImport(raw) {
|
|
136
|
+
const [headers, ...rows] = parseCsv(raw);
|
|
137
|
+
if (!headers || new Set(headers).size !== headers.length || !["url", "name", "utmCampaign", "channels"].every(key => headers.includes(key)))
|
|
138
|
+
throw new Error("CSV requires unique headers: url,name,utmCampaign,channels; optional domain,requestId");
|
|
139
|
+
if (headers.some(key => !["url", "name", "utmCampaign", "channels", "domain", "requestId"].includes(key)) || !rows.length)
|
|
140
|
+
throw new Error("CSV has unknown columns or no data rows");
|
|
141
|
+
const seen = new Set(), requestIds = new Set();
|
|
142
|
+
return { dryRun: true, createsResources: false, rows: rows.map((row, index) => {
|
|
143
|
+
try {
|
|
144
|
+
if (row.length !== headers.length)
|
|
145
|
+
throw new Error("Column count mismatch");
|
|
146
|
+
const values = Object.fromEntries(headers.map((key, i) => [key, row[i]]));
|
|
147
|
+
const draft = validateCampaign({ ...values, domain: values.domain || "linkdevi.com", channels: values.channels.split("|").map(c => c.trim()), ...(values.requestId ? {} : { requestId: undefined }) });
|
|
148
|
+
const identity = JSON.stringify([draft.url, draft.utmCampaign, [...draft.channels].sort()]);
|
|
149
|
+
if (seen.has(identity))
|
|
150
|
+
throw new Error("Duplicate campaign row");
|
|
151
|
+
if (draft.requestId && requestIds.has(draft.requestId))
|
|
152
|
+
throw new Error("Duplicate requestId across rows");
|
|
153
|
+
seen.add(identity);
|
|
154
|
+
if (draft.requestId)
|
|
155
|
+
requestIds.add(draft.requestId);
|
|
156
|
+
return { row: index + 2, valid: true, campaign: draft, preview: previewCampaign(draft) };
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
return { row: index + 2, valid: false, error: error.message };
|
|
160
|
+
}
|
|
161
|
+
}) };
|
|
162
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { LinkDeviClient, LinkDeviError } from "./index.js";
|
|
5
|
+
import { previewCampaign, validateCampaign, launchCsv, planCsvImport } from "./campaign.js";
|
|
6
|
+
const help = `LinkDevi tools — Node 22+
|
|
7
|
+
|
|
8
|
+
linkdevi campaign init [--out campaign.json]
|
|
9
|
+
linkdevi campaign preview campaign.json [--format json|csv]
|
|
10
|
+
linkdevi campaign create campaign.json --confirm
|
|
11
|
+
linkdevi campaign list [--page 1]
|
|
12
|
+
linkdevi campaign stats CAMPAIGN_ID
|
|
13
|
+
linkdevi links import links.csv --dry-run
|
|
14
|
+
linkdevi capabilities
|
|
15
|
+
|
|
16
|
+
Preview, CSV validation and init work offline without an account.
|
|
17
|
+
Remote operations need LINKDEVI_API_KEY; optional LINKDEVI_BASE_URL defaults to https://linkdevi.com.
|
|
18
|
+
Create needs a UUID saved in the input file. Preserve that file unchanged after a timeout.
|
|
19
|
+
CSV import is a preflight only; no bulk write is performed.
|
|
20
|
+
Setup: https://linkdevi.com/features/ai`;
|
|
21
|
+
function read(path) {
|
|
22
|
+
if (!path || path.startsWith("--"))
|
|
23
|
+
throw new Error("Provide an input file");
|
|
24
|
+
const value = readFileSync(path, "utf8");
|
|
25
|
+
if (Buffer.byteLength(value) > 262144)
|
|
26
|
+
throw new Error("Input exceeds 256 KiB");
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
function options(args, allowed) {
|
|
30
|
+
const values = {};
|
|
31
|
+
for (let i = 0; i < args.length; i++) {
|
|
32
|
+
const key = args[i];
|
|
33
|
+
if (!(key in allowed) || key in values)
|
|
34
|
+
throw new Error("Unsupported or repeated argument; use --help");
|
|
35
|
+
if (allowed[key] === "value") {
|
|
36
|
+
const value = args[++i];
|
|
37
|
+
if (!value || value.startsWith("--"))
|
|
38
|
+
throw new Error("Missing option value");
|
|
39
|
+
values[key] = value;
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
values[key] = true;
|
|
43
|
+
}
|
|
44
|
+
return values;
|
|
45
|
+
}
|
|
46
|
+
async function main(args) {
|
|
47
|
+
if (!args.length || (args.length === 1 && ["--help", "-h"].includes(args[0]))) {
|
|
48
|
+
console.log(help);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (args.length === 1 && args[0] === "--version") {
|
|
52
|
+
console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const [group, command, input, ...extra] = args;
|
|
56
|
+
if (group === "campaign" && command === "init") {
|
|
57
|
+
const opts = options(args.slice(2), { "--out": "value" });
|
|
58
|
+
const draft = { requestId: randomUUID(), name: "December launch", url: "https://example.com/sale", utmCampaign: "december-launch", domain: "linkdevi.com", channels: ["facebook", "line", "print"] };
|
|
59
|
+
const output = JSON.stringify(draft, null, 2) + "\n";
|
|
60
|
+
if (opts["--out"])
|
|
61
|
+
writeFileSync(String(opts["--out"]), output, { flag: "wx", mode: 0o600 });
|
|
62
|
+
else
|
|
63
|
+
process.stdout.write(output);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (group === "campaign" && command === "preview") {
|
|
67
|
+
const opts = options(extra, { "--format": "value" });
|
|
68
|
+
if (opts["--format"] && !["json", "csv"].includes(String(opts["--format"])))
|
|
69
|
+
throw new Error("Format must be json or csv");
|
|
70
|
+
const draft = JSON.parse(read(input));
|
|
71
|
+
process.stdout.write(opts["--format"] === "csv" ? launchCsv(draft) + "\n" : JSON.stringify(previewCampaign(draft), null, 2) + "\n");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (group === "links" && command === "import") {
|
|
75
|
+
const opts = options(extra, { "--dry-run": "flag" });
|
|
76
|
+
if (!opts["--dry-run"])
|
|
77
|
+
throw new Error("CSV import currently requires --dry-run");
|
|
78
|
+
const plan = planCsvImport(read(input));
|
|
79
|
+
console.log(JSON.stringify(plan, null, 2));
|
|
80
|
+
if (plan.rows.some(row => !row.valid))
|
|
81
|
+
process.exitCode = 1;
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
// Reject malformed commands before constructing a client or sending a request.
|
|
85
|
+
if (group === "campaign" && command === "create") {
|
|
86
|
+
const opts = options(extra, { "--confirm": "flag" });
|
|
87
|
+
if (!opts["--confirm"])
|
|
88
|
+
throw new Error("Review the preview and add --confirm to create links");
|
|
89
|
+
}
|
|
90
|
+
else if (group === "campaign" && command === "list")
|
|
91
|
+
options(args.slice(2), { "--page": "value" });
|
|
92
|
+
else if (group === "campaign" && command === "stats") {
|
|
93
|
+
options(extra, {});
|
|
94
|
+
if (!input)
|
|
95
|
+
throw new Error("Provide a campaign ID");
|
|
96
|
+
}
|
|
97
|
+
else if (group === "capabilities")
|
|
98
|
+
options(args.slice(1), {});
|
|
99
|
+
else
|
|
100
|
+
throw new Error("Unknown command; use --help");
|
|
101
|
+
const client = new LinkDeviClient({ apiKey: process.env.LINKDEVI_API_KEY ?? "", baseUrl: process.env.LINKDEVI_BASE_URL });
|
|
102
|
+
let result;
|
|
103
|
+
if (group === "capabilities")
|
|
104
|
+
result = await client.capabilities();
|
|
105
|
+
else if (command === "create")
|
|
106
|
+
result = await client.createCampaign(validateCampaign(JSON.parse(read(input)), true));
|
|
107
|
+
else if (command === "list")
|
|
108
|
+
result = await client.listCampaigns(Number(options(args.slice(2), { "--page": "value" })["--page"] ?? 1));
|
|
109
|
+
else
|
|
110
|
+
result = await client.campaignStats(input);
|
|
111
|
+
console.log(JSON.stringify(result, null, 2));
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
await main(process.argv.slice(2));
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
// Never print raw fs/network/parser errors: they may include private paths or inputs.
|
|
118
|
+
if (error instanceof LinkDeviError)
|
|
119
|
+
console.error(JSON.stringify({ error: error.code, status: error.status, retryAfter: error.retryAfter, ambiguous: error.ambiguous, message: error.message }));
|
|
120
|
+
else
|
|
121
|
+
console.error("Command failed. Check input, options and credentials. Use --help; no automatic retry was performed.");
|
|
122
|
+
process.exitCode = 1;
|
|
123
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export * from "./campaign.js";
|
|
2
|
+
import { type CampaignRequest, type CampaignChannel } from "./campaign.js";
|
|
3
|
+
export interface CampaignView {
|
|
4
|
+
id: string;
|
|
5
|
+
name: string;
|
|
6
|
+
url: string;
|
|
7
|
+
utmCampaign: string;
|
|
8
|
+
domain: string;
|
|
9
|
+
channels: {
|
|
10
|
+
key: CampaignChannel;
|
|
11
|
+
link: null | {
|
|
12
|
+
id: string;
|
|
13
|
+
shortUrl: string;
|
|
14
|
+
url: string;
|
|
15
|
+
clicks: number;
|
|
16
|
+
active: boolean;
|
|
17
|
+
};
|
|
18
|
+
}[];
|
|
19
|
+
}
|
|
20
|
+
export interface CampaignResult {
|
|
21
|
+
campaign: CampaignView;
|
|
22
|
+
reused: boolean;
|
|
23
|
+
managePath?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface Capabilities {
|
|
26
|
+
workspaceId: string;
|
|
27
|
+
scopes: string[];
|
|
28
|
+
plan: string;
|
|
29
|
+
limits: Record<string, unknown>;
|
|
30
|
+
usage: {
|
|
31
|
+
storedLinks: number;
|
|
32
|
+
};
|
|
33
|
+
counterDefinition: Record<string, unknown>;
|
|
34
|
+
}
|
|
35
|
+
export declare class LinkDeviError extends Error {
|
|
36
|
+
status: number;
|
|
37
|
+
code: string;
|
|
38
|
+
retryAfter: number | null;
|
|
39
|
+
ambiguous: boolean;
|
|
40
|
+
constructor(status: number, code: string, retryAfter?: number | null, ambiguous?: boolean);
|
|
41
|
+
}
|
|
42
|
+
export declare class LinkDeviClient {
|
|
43
|
+
private origin;
|
|
44
|
+
private apiKey;
|
|
45
|
+
private fetchImpl;
|
|
46
|
+
constructor(options: {
|
|
47
|
+
apiKey: string;
|
|
48
|
+
baseUrl?: string;
|
|
49
|
+
fetch?: typeof fetch;
|
|
50
|
+
});
|
|
51
|
+
private call;
|
|
52
|
+
capabilities(): Promise<Capabilities>;
|
|
53
|
+
previewCampaign(campaign: CampaignRequest): Promise<{
|
|
54
|
+
linksToCreate: number;
|
|
55
|
+
channels: {
|
|
56
|
+
channel: "facebook" | "instagram" | "tiktok" | "line" | "email" | "youtube" | "x" | "print";
|
|
57
|
+
destinationUrl: string;
|
|
58
|
+
}[];
|
|
59
|
+
createsResources: false;
|
|
60
|
+
requestId?: string | undefined;
|
|
61
|
+
}>;
|
|
62
|
+
createCampaign(campaign: CampaignRequest): Promise<CampaignResult>;
|
|
63
|
+
listCampaigns(page?: number): Promise<{
|
|
64
|
+
items: CampaignView[];
|
|
65
|
+
total: number;
|
|
66
|
+
page: number;
|
|
67
|
+
pageSize: number;
|
|
68
|
+
}>;
|
|
69
|
+
campaignStats(campaignId: string): Promise<{
|
|
70
|
+
campaign: CampaignView;
|
|
71
|
+
observedAt: string;
|
|
72
|
+
counterDefinition: Record<string, unknown>;
|
|
73
|
+
unavailableChannels: CampaignChannel[];
|
|
74
|
+
}>;
|
|
75
|
+
linkQr(linkId: string, size?: number): Promise<{
|
|
76
|
+
linkId: string;
|
|
77
|
+
shortUrl: string;
|
|
78
|
+
qrDataUrl: string;
|
|
79
|
+
persistsResource: false;
|
|
80
|
+
}>;
|
|
81
|
+
private id;
|
|
82
|
+
}
|