@knock-ai/sdk 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +166 -0
  3. package/angular/package.json +7 -0
  4. package/contract/package.json +7 -0
  5. package/dist/angular.cjs +2 -0
  6. package/dist/angular.cjs.map +1 -0
  7. package/dist/angular.js +2 -0
  8. package/dist/angular.js.map +1 -0
  9. package/dist/contract.cjs +2 -0
  10. package/dist/contract.cjs.map +1 -0
  11. package/dist/contract.js +2 -0
  12. package/dist/contract.js.map +1 -0
  13. package/dist/index.cjs +3 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.js +3 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/knockai.iife.js +3 -0
  18. package/dist/knockai.iife.js.map +1 -0
  19. package/dist/react.cjs +2 -0
  20. package/dist/react.cjs.map +1 -0
  21. package/dist/react.js +2 -0
  22. package/dist/react.js.map +1 -0
  23. package/dist/snippet.js +3 -0
  24. package/dist/snippet.js.map +1 -0
  25. package/dist/testing.cjs +2 -0
  26. package/dist/testing.cjs.map +1 -0
  27. package/dist/testing.js +2 -0
  28. package/dist/testing.js.map +1 -0
  29. package/dist/types/core/bridge.d.cts +6 -0
  30. package/dist/types/core/bridge.d.ts +7 -0
  31. package/dist/types/core/bridge.d.ts.map +1 -0
  32. package/dist/types/core/contract.d.cts +4 -0
  33. package/dist/types/core/contract.d.ts +5 -0
  34. package/dist/types/core/contract.d.ts.map +1 -0
  35. package/dist/types/core/emitter.d.cts +7 -0
  36. package/dist/types/core/emitter.d.ts +8 -0
  37. package/dist/types/core/emitter.d.ts.map +1 -0
  38. package/dist/types/core/env.d.cts +2 -0
  39. package/dist/types/core/env.d.ts +3 -0
  40. package/dist/types/core/env.d.ts.map +1 -0
  41. package/dist/types/core/globals.d.cts +21 -0
  42. package/dist/types/core/globals.d.ts +22 -0
  43. package/dist/types/core/globals.d.ts.map +1 -0
  44. package/dist/types/core/iife.d.cts +7 -0
  45. package/dist/types/core/iife.d.ts +8 -0
  46. package/dist/types/core/iife.d.ts.map +1 -0
  47. package/dist/types/core/index.d.cts +22 -0
  48. package/dist/types/core/index.d.ts +23 -0
  49. package/dist/types/core/index.d.ts.map +1 -0
  50. package/dist/types/core/loader.d.cts +9 -0
  51. package/dist/types/core/loader.d.ts +10 -0
  52. package/dist/types/core/loader.d.ts.map +1 -0
  53. package/dist/types/core/queue.d.cts +16 -0
  54. package/dist/types/core/queue.d.ts +17 -0
  55. package/dist/types/core/queue.d.ts.map +1 -0
  56. package/dist/types/core/snippet.d.cts +1 -0
  57. package/dist/types/core/snippet.d.ts +2 -0
  58. package/dist/types/core/snippet.d.ts.map +1 -0
  59. package/dist/types/core/types.d.cts +148 -0
  60. package/dist/types/core/types.d.ts +149 -0
  61. package/dist/types/core/types.d.ts.map +1 -0
  62. package/dist/types/core/version.d.cts +1 -0
  63. package/dist/types/core/version.d.ts +2 -0
  64. package/dist/types/core/version.d.ts.map +1 -0
  65. package/dist/types/core/wire.d.cts +66 -0
  66. package/dist/types/core/wire.d.ts +67 -0
  67. package/dist/types/core/wire.d.ts.map +1 -0
  68. package/dist/types/frameworks/angular/index.d.cts +2 -0
  69. package/dist/types/frameworks/angular/index.d.ts +3 -0
  70. package/dist/types/frameworks/angular/index.d.ts.map +1 -0
  71. package/dist/types/frameworks/angular/knock.token.d.cts +4 -0
  72. package/dist/types/frameworks/angular/knock.token.d.ts +5 -0
  73. package/dist/types/frameworks/angular/knock.token.d.ts.map +1 -0
  74. package/dist/types/frameworks/angular/provide-knock.d.cts +4 -0
  75. package/dist/types/frameworks/angular/provide-knock.d.ts +5 -0
  76. package/dist/types/frameworks/angular/provide-knock.d.ts.map +1 -0
  77. package/dist/types/frameworks/react/KnockButton.d.cts +9 -0
  78. package/dist/types/frameworks/react/KnockButton.d.ts +10 -0
  79. package/dist/types/frameworks/react/KnockButton.d.ts.map +1 -0
  80. package/dist/types/frameworks/react/KnockProvider.d.cts +10 -0
  81. package/dist/types/frameworks/react/KnockProvider.d.ts +11 -0
  82. package/dist/types/frameworks/react/KnockProvider.d.ts.map +1 -0
  83. package/dist/types/frameworks/react/context.d.cts +3 -0
  84. package/dist/types/frameworks/react/context.d.ts +4 -0
  85. package/dist/types/frameworks/react/context.d.ts.map +1 -0
  86. package/dist/types/frameworks/react/index.d.cts +7 -0
  87. package/dist/types/frameworks/react/index.d.ts +8 -0
  88. package/dist/types/frameworks/react/index.d.ts.map +1 -0
  89. package/dist/types/frameworks/react/useKnock.d.cts +2 -0
  90. package/dist/types/frameworks/react/useKnock.d.ts +3 -0
  91. package/dist/types/frameworks/react/useKnock.d.ts.map +1 -0
  92. package/dist/types/frameworks/react/useKnockEvent.d.cts +2 -0
  93. package/dist/types/frameworks/react/useKnockEvent.d.ts +3 -0
  94. package/dist/types/frameworks/react/useKnockEvent.d.ts.map +1 -0
  95. package/dist/types/frameworks/react/useKnockIdentify.d.cts +2 -0
  96. package/dist/types/frameworks/react/useKnockIdentify.d.ts +3 -0
  97. package/dist/types/frameworks/react/useKnockIdentify.d.ts.map +1 -0
  98. package/dist/types/frameworks/vue/button.d.cts +29 -0
  99. package/dist/types/frameworks/vue/button.d.ts +30 -0
  100. package/dist/types/frameworks/vue/button.d.ts.map +1 -0
  101. package/dist/types/frameworks/vue/index.d.cts +4 -0
  102. package/dist/types/frameworks/vue/index.d.ts +5 -0
  103. package/dist/types/frameworks/vue/index.d.ts.map +1 -0
  104. package/dist/types/frameworks/vue/inject-key.d.cts +3 -0
  105. package/dist/types/frameworks/vue/inject-key.d.ts +4 -0
  106. package/dist/types/frameworks/vue/inject-key.d.ts.map +1 -0
  107. package/dist/types/frameworks/vue/plugin.d.cts +5 -0
  108. package/dist/types/frameworks/vue/plugin.d.ts +6 -0
  109. package/dist/types/frameworks/vue/plugin.d.ts.map +1 -0
  110. package/dist/types/frameworks/vue/use-knock.d.cts +2 -0
  111. package/dist/types/frameworks/vue/use-knock.d.ts +3 -0
  112. package/dist/types/frameworks/vue/use-knock.d.ts.map +1 -0
  113. package/dist/types/testing/index.d.cts +61 -0
  114. package/dist/types/testing/index.d.ts +62 -0
  115. package/dist/types/testing/index.d.ts.map +1 -0
  116. package/dist/vue.cjs +2 -0
  117. package/dist/vue.cjs.map +1 -0
  118. package/dist/vue.js +2 -0
  119. package/dist/vue.js.map +1 -0
  120. package/package.json +231 -0
  121. package/react/package.json +7 -0
  122. package/testing/package.json +7 -0
  123. package/vue/package.json +7 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Knock AI Ltd.
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 ADDED
@@ -0,0 +1,166 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="assets/knock-logo-dark.svg">
4
+ <img alt="Knock" src="assets/knock-logo.svg" width="160">
5
+ </picture>
6
+ </p>
7
+
8
+ <p align="center"><strong>@knock-ai/sdk</strong> — the Knock AI SDK for your website and your logged-in app</p>
9
+
10
+ <p align="center">
11
+ <a href="https://www.npmjs.com/package/@knock-ai/sdk"><img alt="npm: @knock-ai/sdk" src="https://img.shields.io/badge/npm-%40knock--ai%2Fsdk-cb3837"></a>
12
+ <a href="#compatibility"><img alt="core size" src="https://img.shields.io/badge/core-%E2%89%A41.7%20kB%20gzip-506bff"></a>
13
+ <a href="#compatibility"><img alt="zero dependencies" src="https://img.shields.io/badge/dependencies-0-506bff"></a>
14
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg"></a>
15
+ </p>
16
+
17
+ ---
18
+
19
+ `@knock-ai/sdk` lets your code tell Knock who a person is, record what they do, and open your Knock
20
+ scheduling modal, on your marketing site or in your logged-in app. It loads your Knock tag for you
21
+ and queues your calls until it's ready, so you never have to wait for it. It's typed, has zero
22
+ dependencies, and the core is ≤ 1.7 KB gzip.
23
+
24
+ ## Install with your AI agent
25
+
26
+ 1. Add the install skill to your coding agent:
27
+
28
+ ```bash
29
+ npx skills add knock-org/knock-sdk
30
+ ```
31
+
32
+ It installs the skill for the agents it detects (Claude Code, Codex, Cursor, GitHub Copilot,
33
+ Gemini CLI, Windsurf, OpenCode and others). To choose, add `-a <agent>`, for example `-a cursor`.
34
+ 2. Ask your agent to install the Knock SDK. In Claude Code you can type `/install-knock-sdk`, and
35
+ in Codex `$install-knock-sdk`.
36
+
37
+ It tells you what it will do and asks before it starts. Then it looks through your project, suggests
38
+ events to track, asks for your tag id, shows you a plan, and installs `@knock-ai/sdk`.
39
+
40
+ If your agent doesn't support skills, paste this into it:
41
+
42
+ ```text
43
+ Install the Knock SDK by following https://raw.githubusercontent.com/knock-org/knock-sdk/main/skills/install-knock-sdk/SKILL.md
44
+ ```
45
+
46
+ ## Install
47
+
48
+ ### npm
49
+
50
+ ```bash
51
+ npm install @knock-ai/sdk
52
+ ```
53
+
54
+ ```ts
55
+ import { knock } from '@knock-ai/sdk';
56
+
57
+ knock.init({ tagId: 'YOUR_TAG_ID' });
58
+
59
+ knock.identify({ email: user.email, firstName: user.firstName });
60
+ ```
61
+
62
+ ### CDN (no build step)
63
+
64
+ Paste this once in `<head>`. It works the same as the npm package: the code after it can call
65
+ `knock.identify()`, `knock.track()` or `knock.modal.open()` right away.
66
+
67
+ <!-- knockai-snippet:start -->
68
+ ```html
69
+ <script>
70
+ (function(){'use strict';function w(i){return !!i&&Array.isArray(i.q)}function u(i){return !i||w(i)||i.__knockai===true}var f="https://cdn.jsdelivr.net/npm/@knock-ai/sdk@0.1/dist/knockai.iife.js",S=["init","identify","track","modal.open","modal.close","widget.show","widget.hide","widget.open","widget.close"];(function(){var d,k,l;if(typeof window=="undefined"||window.knockai)return;let r=u(window.knock),s=[],t={q:s,ready:false};for(let c of S){let[n,e]=c.split("."),o=(...p)=>{s.push([c,p]);};e?((d=t[n])!=null?d:t[n]={})[e]=o:t[n]=o;}t.on=(...c)=>{let n,e=["on",c,o=>n=o];return s.push(e),()=>n?n():void(e[0]="")},t.scheduling={load(...c){let n;s.push(["scheduling.load",c,o=>n=o]);let e=o=>()=>n?n[o]():s.push([()=>n[o](),[]]);return {open:e("open"),close:e("close"),get status(){return n?n.status:"loading"}}}},window.knockai=t,r?window.knock=t:console.warn("[knockai] window.knock is taken by this page \u2014 use window.knockai instead");let a=document.createElement("script");a.async=true,a.src=(l=(k=document.currentScript)==null?void 0:k.dataset.knockaiSrc)!=null?l:f,document.head.appendChild(a);})();
71
+ })();
72
+ knockai.init({ tagId: 'YOUR_TAG_ID' });
73
+ </script>
74
+ ```
75
+ <!-- knockai-snippet:end -->
76
+
77
+ The snippet defines `window.knock`, plus `window.knockai` for pages that already use the name
78
+ `knock`. A full page: [`examples/vanilla/index.html`](examples/vanilla/index.html).
79
+
80
+ ## One SDK, two tags
81
+
82
+ Your Knock workspace has two tags. Pass the right one's id to `init()`. The API is the same on both.
83
+
84
+ | Where | `tagId` | What `identify()` does | Captured automatically |
85
+ |---|---|---|---|
86
+ | Your marketing site | Your website tag's id | Captures a lead. Knock may research the lead's company to help your sales team. | What your website tag is set up to capture (page views, clicks, forms) |
87
+ | Your logged-in app | Your product tag's id | Tells Knock which signed-in customer this is. Knock doesn't start its website lead research for them. | Nothing by default: only your `track()` and `identify()` calls, plus clicks on Knock's widget if you show it |
88
+
89
+ Once the SDK is ready, `knock.surface` is `'website'` or `'product'`. It's `undefined` before that,
90
+ and on older Knock tags.
91
+
92
+ ## Identify
93
+
94
+ ```ts
95
+ knock.identify({
96
+ email: 'jane@acme.com', // required
97
+ firstName: 'Jane',
98
+ company: 'Acme',
99
+ });
100
+ ```
101
+
102
+ More in [`docs/identify.md`](docs/identify.md).
103
+
104
+ ## Track events
105
+
106
+ ```ts
107
+ knock.track('trial_started', { plan: 'pro' });
108
+ ```
109
+
110
+ Names and limits: [`docs/events.md`](docs/events.md).
111
+
112
+ ## Open the scheduling modal
113
+
114
+ ```ts
115
+ knock.modal.open({ magicLinkId: 'a1b2c3', email: user.email });
116
+
117
+ knock.modal.open(); // your default Knock modal
118
+ ```
119
+
120
+ To start loading times before you open it, use `knock.scheduling.load()`. See
121
+ [`docs/widget-and-modals.md`](docs/widget-and-modals.md).
122
+
123
+ ## React
124
+
125
+ ```tsx
126
+ import { KnockProvider, KnockButton } from '@knock-ai/sdk/react';
127
+
128
+ function App() {
129
+ return (
130
+ <KnockProvider tagId="YOUR_TAG_ID">
131
+ <KnockButton magicLinkId="a1b2c3">Book a demo</KnockButton>
132
+ </KnockProvider>
133
+ );
134
+ }
135
+ ```
136
+
137
+ Vue and Angular too: [`docs/frameworks/`](docs/frameworks/).
138
+
139
+ ## Compatibility
140
+
141
+ | | Declared support |
142
+ |---|---|
143
+ | React | 17+ (optional) |
144
+ | Vue | 3+ (optional) |
145
+ | Angular | 17+ (optional) |
146
+
147
+ Install only the framework you use. The package ships ES modules and CommonJS with TypeScript
148
+ types, compiled to ES2019. On the server every call does nothing, so it's safe to import from
149
+ server-rendered code.
150
+
151
+ ## Docs
152
+
153
+ | | |
154
+ |---|---|
155
+ | [Quickstart](docs/quickstart.md) | Install, `init()`, your first `identify()` and `track()` |
156
+ | [Identify](docs/identify.md) | What `identify()` does on each tag, and what to send |
157
+ | [Events](docs/events.md) | `track()`: names, properties, limits |
158
+ | [Scheduling modal and widget](docs/widget-and-modals.md) | `modal.open()`, `scheduling.load()`, buttons, `on()` |
159
+ | [Frameworks](docs/frameworks/) | React, Vue, Angular, plain JavaScript |
160
+ | [Platforms](docs/platforms.md) | Shopify, Wix, Webflow, Framer, WordPress, AI app builders |
161
+ | [CSP](docs/csp.md) | Content-Security-Policy |
162
+ | [FAQ](docs/faq.md) | Common questions |
163
+
164
+ ## License
165
+
166
+ [MIT](LICENSE) © 2026 Knock AI Ltd.
@@ -0,0 +1,7 @@
1
+ {
2
+ "private": true,
3
+ "main": "../dist/angular.cjs",
4
+ "module": "../dist/angular.js",
5
+ "types": "../dist/types/frameworks/angular/index.d.ts",
6
+ "sideEffects": false
7
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "private": true,
3
+ "main": "../dist/contract.cjs",
4
+ "module": "../dist/contract.js",
5
+ "types": "../dist/types/core/contract.d.ts",
6
+ "sideEffects": false
7
+ }
@@ -0,0 +1,2 @@
1
+ 'use strict';var core=require('@angular/core'),sdk=require('@knock-ai/sdk');function t(o){sdk.knock.init(o);}function e(o){return core.makeEnvironmentProviders([{provide:core.APP_INITIALIZER,multi:true,useValue:()=>t(o)}])}var m=new core.InjectionToken("@knock-ai/sdk",{providedIn:"root",factory:()=>sdk.knock});exports.KNOCK=m;exports.provideKnock=e;//# sourceMappingURL=angular.cjs.map
2
+ //# sourceMappingURL=angular.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/frameworks/angular/provide-knock.ts","../src/frameworks/angular/knock.token.ts"],"names":["initKnockRuntime","options","knock","provideKnock","makeEnvironmentProviders","APP_INITIALIZER","KNOCK","InjectionToken"],"mappings":"4EAIO,SAASA,CAAAA,CAAiBC,CAAAA,CAAiC,CAChEC,SAAAA,CAAM,IAAA,CAAKD,CAAO,EACpB,CAIO,SAASE,CAAAA,CAAaF,CAAAA,CAAiD,CAC5E,OAAOG,6BAAAA,CAAyB,CAC9B,CACE,OAAA,CAASC,oBAAAA,CACT,KAAA,CAAO,KACP,QAAA,CAAU,IAAML,CAAAA,CAAiBC,CAAO,CAC1C,CACF,CAAC,CACH,CCbO,IAAMK,CAAAA,CAAQ,IAAIC,mBAAAA,CAAyB,eAAA,CAAiB,CAAE,UAAA,CAAY,MAAA,CAAQ,OAAA,CAAS,IAAML,SAAM,CAAC","file":"angular.cjs","sourcesContent":["import { APP_INITIALIZER, makeEnvironmentProviders, type EnvironmentProviders } from '@angular/core';\nimport type { KnockInitOptions } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\n\nexport function initKnockRuntime(options: KnockInitOptions): void {\n knock.init(options);\n}\n\n// APP_INITIALIZER (not provideAppInitializer) to stay compatible with the package's\n// declared >=17 Angular peer range; still a plain EnvironmentProviders, no NgModule.\nexport function provideKnock(options: KnockInitOptions): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: APP_INITIALIZER,\n multi: true,\n useValue: () => initKnockRuntime(options),\n },\n ]);\n}\n","import { InjectionToken } from '@angular/core';\nimport type { KnockSDK } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\n\n/** `inject(KNOCK)` returns the shared `knock` instance. A runtime token, so it needs no Angular compiler output. */\nexport const KNOCK = new InjectionToken<KnockSDK>('@knock-ai/sdk', { providedIn: 'root', factory: () => knock });\n"]}
@@ -0,0 +1,2 @@
1
+ import {InjectionToken,makeEnvironmentProviders,APP_INITIALIZER}from'@angular/core';import {knock}from'@knock-ai/sdk';function t(o){knock.init(o);}function e(o){return makeEnvironmentProviders([{provide:APP_INITIALIZER,multi:true,useValue:()=>t(o)}])}var m=new InjectionToken("@knock-ai/sdk",{providedIn:"root",factory:()=>knock});export{m as KNOCK,e as provideKnock};//# sourceMappingURL=angular.js.map
2
+ //# sourceMappingURL=angular.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/frameworks/angular/provide-knock.ts","../src/frameworks/angular/knock.token.ts"],"names":["initKnockRuntime","options","knock","provideKnock","makeEnvironmentProviders","APP_INITIALIZER","KNOCK","InjectionToken"],"mappings":"sHAIO,SAASA,CAAAA,CAAiBC,CAAAA,CAAiC,CAChEC,KAAAA,CAAM,IAAA,CAAKD,CAAO,EACpB,CAIO,SAASE,CAAAA,CAAaF,CAAAA,CAAiD,CAC5E,OAAOG,wBAAAA,CAAyB,CAC9B,CACE,OAAA,CAASC,eAAAA,CACT,KAAA,CAAO,KACP,QAAA,CAAU,IAAML,CAAAA,CAAiBC,CAAO,CAC1C,CACF,CAAC,CACH,CCbO,IAAMK,CAAAA,CAAQ,IAAIC,cAAAA,CAAyB,eAAA,CAAiB,CAAE,UAAA,CAAY,MAAA,CAAQ,OAAA,CAAS,IAAML,KAAM,CAAC","file":"angular.js","sourcesContent":["import { APP_INITIALIZER, makeEnvironmentProviders, type EnvironmentProviders } from '@angular/core';\nimport type { KnockInitOptions } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\n\nexport function initKnockRuntime(options: KnockInitOptions): void {\n knock.init(options);\n}\n\n// APP_INITIALIZER (not provideAppInitializer) to stay compatible with the package's\n// declared >=17 Angular peer range; still a plain EnvironmentProviders, no NgModule.\nexport function provideKnock(options: KnockInitOptions): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: APP_INITIALIZER,\n multi: true,\n useValue: () => initKnockRuntime(options),\n },\n ]);\n}\n","import { InjectionToken } from '@angular/core';\nimport type { KnockSDK } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\n\n/** `inject(KNOCK)` returns the shared `knock` instance. A runtime token, so it needs no Angular compiler output. */\nexport const KNOCK = new InjectionToken<KnockSDK>('@knock-ai/sdk', { providedIn: 'root', factory: () => knock });\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var t={retryOn:[408,429,500,502,503,504],neverRetryOn:[400,401,403],maxAttempts:10,maxNetworkAttempts:3,initialBackoffMs:3e3,maxBackoffMs:3e5,jitter:.25,maxRetryAfterMs:3e4},n={maxEventsPerBatch:50,maxBatchBytes:64*1024,flushIntervalMs:1e3},e={param:"e",format:"gzip",minBytes:1024},r=/^[a-z][a-z0-9_]{0,63}$/;exports.WIRE_BATCH_POLICY=n;exports.WIRE_COMPRESSION=e;exports.WIRE_EVENT_NAME_PATTERN=r;exports.WIRE_RETRY_POLICY=t;//# sourceMappingURL=contract.cjs.map
2
+ //# sourceMappingURL=contract.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/wire.ts"],"names":["WIRE_RETRY_POLICY","WIRE_BATCH_POLICY","WIRE_COMPRESSION","WIRE_EVENT_NAME_PATTERN"],"mappings":"aAQO,IAAMA,CAAAA,CAAoB,CAC/B,OAAA,CAAS,CAAC,IAAK,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAG,CAAA,CACtC,aAAc,CAAC,GAAA,CAAK,IAAK,GAAG,CAAA,CAC5B,YAAa,EAAA,CAEb,kBAAA,CAAoB,CAAA,CACpB,gBAAA,CAAkB,GAAA,CAClB,YAAA,CAAc,IACd,MAAA,CAAQ,GAAA,CAER,gBAAiB,GACnB,CAAA,CAGaC,EAAoB,CAC/B,iBAAA,CAAmB,EAAA,CACnB,aAAA,CAAe,EAAA,CAAK,IAAA,CACpB,gBAAiB,GACnB,CAAA,CAGaC,CAAAA,CAAmB,CAAE,KAAA,CAAO,GAAA,CAAK,OAAQ,MAAA,CAAQ,QAAA,CAAU,IAAK,CAAA,CAMhEC,CAAAA,CAA0B","file":"contract.cjs","sourcesContent":["/**\n * Wire protocol: what a conforming runtime sends for `track()` — `POST <ingest>/client/an/v1/product-events`.\n * The facade never touches the network — these shapes bind the runtime (the Knock tag). On the product tag,\n * `identify()` is sent here too, as the reserved `$identify` event.\n */\nimport type { KnockTagSurface } from './types.js';\n\n/** Retry policy every runtime must implement (posthog-js backoff). Status codes not listed are not retried. */\nexport const WIRE_RETRY_POLICY = {\n retryOn: [408, 429, 500, 502, 503, 504],\n neverRetryOn: [400, 401, 403],\n maxAttempts: 10,\n /** No HTTP response at all (usually an ad blocker). Offline time doesn't count. */\n maxNetworkAttempts: 3,\n initialBackoffMs: 3000,\n maxBackoffMs: 300_000,\n jitter: 0.25,\n /** `Retry-After` (seconds) is a floor on the next delay, itself capped. */\n maxRetryAfterMs: 30_000,\n} as const;\n\n/** The server caps a request body at 64 KB and a batch at 50 events; a 413 halves the batch. */\nexport const WIRE_BATCH_POLICY = {\n maxEventsPerBatch: 50,\n maxBatchBytes: 64 * 1024,\n flushIntervalMs: 1000,\n} as const;\n\n/** Bodies at least this large are gzipped and named in `?e=gzip` (sendBeacon can't set Content-Encoding). */\nexport const WIRE_COMPRESSION = { param: 'e', format: 'gzip', minBytes: 1024 } as const;\n\n/**\n * Server-enforced event name. The runtime normalizes a vendor's name onto it (`Signed up` → `signed_up`)\n * and a name that can't be normalized is dropped — one invalid event rejects its whole batch.\n */\nexport const WIRE_EVENT_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;\n\nexport interface KnockWireEvent {\n /** A unique id per event (`[A-Za-z0-9_-]{8,64}`), minted once at call time and identical on every retry. */\n eventId: string;\n /** Normalized to `WIRE_EVENT_NAME_PATTERN`, or the runtime's reserved `$identify` (properties = traits, `email` required). */\n name: string;\n /** ISO-8601 time of the vendor's call, unchanged on retry. The server keeps it only within ±24 h. */\n occurredAt: string;\n /** JSON values, ≤ 3 levels of nesting, ≤ 100 keys, arrays ≤ 50, strings ≤ 1 KB, ~8 KB serialized. */\n properties?: Record<string, unknown>;\n}\n\n/** One request: the session context once, then the events. Keys match the tag's analytics rows. */\nexport interface KnockWireBatch {\n vendorId: string;\n /** Knock's visitor id from `/uid2` (`<uuid>.<mintedAtMs>`) — required; the runtime holds events until it exists. */\n userId: string;\n sessionId: string | null;\n /** Required: the sending tag's id. */\n tagId: string;\n tagVersion: string | null;\n /** Which tag sent the batch; absent from tags that predate it. */\n surface?: KnockTagSurface;\n pageVisit: string | null;\n referrerUrl: string | null;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_content?: string;\n utm_term?: string;\n events: KnockWireEvent[];\n}\n"]}
@@ -0,0 +1,2 @@
1
+ var t={retryOn:[408,429,500,502,503,504],neverRetryOn:[400,401,403],maxAttempts:10,maxNetworkAttempts:3,initialBackoffMs:3e3,maxBackoffMs:3e5,jitter:.25,maxRetryAfterMs:3e4},n={maxEventsPerBatch:50,maxBatchBytes:64*1024,flushIntervalMs:1e3},e={param:"e",format:"gzip",minBytes:1024},r=/^[a-z][a-z0-9_]{0,63}$/;export{n as WIRE_BATCH_POLICY,e as WIRE_COMPRESSION,r as WIRE_EVENT_NAME_PATTERN,t as WIRE_RETRY_POLICY};//# sourceMappingURL=contract.js.map
2
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/wire.ts"],"names":["WIRE_RETRY_POLICY","WIRE_BATCH_POLICY","WIRE_COMPRESSION","WIRE_EVENT_NAME_PATTERN"],"mappings":"AAQO,IAAMA,CAAAA,CAAoB,CAC/B,OAAA,CAAS,CAAC,IAAK,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAA,CAAK,GAAG,CAAA,CACtC,aAAc,CAAC,GAAA,CAAK,IAAK,GAAG,CAAA,CAC5B,YAAa,EAAA,CAEb,kBAAA,CAAoB,CAAA,CACpB,gBAAA,CAAkB,GAAA,CAClB,YAAA,CAAc,IACd,MAAA,CAAQ,GAAA,CAER,gBAAiB,GACnB,CAAA,CAGaC,EAAoB,CAC/B,iBAAA,CAAmB,EAAA,CACnB,aAAA,CAAe,EAAA,CAAK,IAAA,CACpB,gBAAiB,GACnB,CAAA,CAGaC,CAAAA,CAAmB,CAAE,KAAA,CAAO,GAAA,CAAK,OAAQ,MAAA,CAAQ,QAAA,CAAU,IAAK,CAAA,CAMhEC,CAAAA,CAA0B","file":"contract.js","sourcesContent":["/**\n * Wire protocol: what a conforming runtime sends for `track()` — `POST <ingest>/client/an/v1/product-events`.\n * The facade never touches the network — these shapes bind the runtime (the Knock tag). On the product tag,\n * `identify()` is sent here too, as the reserved `$identify` event.\n */\nimport type { KnockTagSurface } from './types.js';\n\n/** Retry policy every runtime must implement (posthog-js backoff). Status codes not listed are not retried. */\nexport const WIRE_RETRY_POLICY = {\n retryOn: [408, 429, 500, 502, 503, 504],\n neverRetryOn: [400, 401, 403],\n maxAttempts: 10,\n /** No HTTP response at all (usually an ad blocker). Offline time doesn't count. */\n maxNetworkAttempts: 3,\n initialBackoffMs: 3000,\n maxBackoffMs: 300_000,\n jitter: 0.25,\n /** `Retry-After` (seconds) is a floor on the next delay, itself capped. */\n maxRetryAfterMs: 30_000,\n} as const;\n\n/** The server caps a request body at 64 KB and a batch at 50 events; a 413 halves the batch. */\nexport const WIRE_BATCH_POLICY = {\n maxEventsPerBatch: 50,\n maxBatchBytes: 64 * 1024,\n flushIntervalMs: 1000,\n} as const;\n\n/** Bodies at least this large are gzipped and named in `?e=gzip` (sendBeacon can't set Content-Encoding). */\nexport const WIRE_COMPRESSION = { param: 'e', format: 'gzip', minBytes: 1024 } as const;\n\n/**\n * Server-enforced event name. The runtime normalizes a vendor's name onto it (`Signed up` → `signed_up`)\n * and a name that can't be normalized is dropped — one invalid event rejects its whole batch.\n */\nexport const WIRE_EVENT_NAME_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;\n\nexport interface KnockWireEvent {\n /** A unique id per event (`[A-Za-z0-9_-]{8,64}`), minted once at call time and identical on every retry. */\n eventId: string;\n /** Normalized to `WIRE_EVENT_NAME_PATTERN`, or the runtime's reserved `$identify` (properties = traits, `email` required). */\n name: string;\n /** ISO-8601 time of the vendor's call, unchanged on retry. The server keeps it only within ±24 h. */\n occurredAt: string;\n /** JSON values, ≤ 3 levels of nesting, ≤ 100 keys, arrays ≤ 50, strings ≤ 1 KB, ~8 KB serialized. */\n properties?: Record<string, unknown>;\n}\n\n/** One request: the session context once, then the events. Keys match the tag's analytics rows. */\nexport interface KnockWireBatch {\n vendorId: string;\n /** Knock's visitor id from `/uid2` (`<uuid>.<mintedAtMs>`) — required; the runtime holds events until it exists. */\n userId: string;\n sessionId: string | null;\n /** Required: the sending tag's id. */\n tagId: string;\n tagVersion: string | null;\n /** Which tag sent the batch; absent from tags that predate it. */\n surface?: KnockTagSurface;\n pageVisit: string | null;\n referrerUrl: string | null;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_content?: string;\n utm_term?: string;\n events: KnockWireEvent[];\n}\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var k=class{constructor(){this.handlers=new Map;}on(o,t){let i=t,r=this.handlers.get(o);return r||(r=new Set,this.handlers.set(o,r)),r.add(i),()=>{r.delete(i);}}emit(o,t){let i=this.handlers.get(o);if(i)for(let r of i)r(t);}clear(){this.handlers.clear();}};var b="[knockai]";function E(){let n,o;return {attach(t){n=t,o&&t[o]();},open(){n?n.open():o="open";},close(){n?n.close():o="close";},get status(){return n?n.status:"loading"}}}function N(n,o){let[t,i]=o.split("."),r=i?Reflect.get(n,t):n;return {self:r,fn:r?Reflect.get(r,i!=null?i:t):void 0}}function K(n,o,t){let{path:i,args:r}=o,{fn:s,self:l}=N(n,i);if(typeof s=="function"){let p=s.apply(l,r);o.handle&&o.handle.attach(p);return}if(i==="modal.open"){n.scheduling.load(r[0]).open();return}t&&console.warn(b,`no runtime ${i} \u2014 ignored`);}var j={production:"knock-tag-build/prod",staging:"knock-tag-build-stg/prod",development:"knock-tag-build/dev"};function y(n){return j[n]}var _="knockai-runtime",L=/knock-ai\.com\/|knock-tag/;function H(){return [...document.scripts].some(n=>n.id===_||L.test(n.src))}function I(){var n,o;return [...(o=(n=window.__knockTagInstances)==null?void 0:n.values())!=null?o:[]].map(t=>t.tagId)}function R(n,o,t){return t||`https://storage.googleapis.com/${y(n)}/${o}/latest/index.js`}function O(n){typeof window!="undefined"&&(window.__KNOCK_SDK__=n);}function x(n){if(typeof document=="undefined"||H())return;let o=document.createElement("script");o.id=_,o.async=true,o.src=n,document.head.appendChild(o);}var m="0.1.2";var u="[knockai]",M=1e3,B=["modal:open","modal:close","widget:open","widget:close","error"];function g(){return typeof window!="undefined"}function V(){let n=false,o=false,t=false,i,r,s=new k,l=[];function p(){return o&&g()?window.Knock:void 0}function h(e){return e.email||!i?e:{...e,email:i}}function f(e){if(!g())return;let c=p();c?K(c,e,t):v(e);}function v(e){l.length<M?l.push(e):t&&console.warn(u,`${M} calls queued before Knock loaded \u2014 ${e.path} dropped`);}function S(){var c;if(o)return;o=true;let e=p();if(!e){t&&console.warn(u,"ready without window.Knock");return}(e.surface==="website"||e.surface==="product")&&(r=e.surface);for(let d of l.splice(0))try{K(e,d,t);}catch(a){t&&console.warn(u,d.path,a);}for(let d of B)(c=e.on)==null||c.call(e,d,a=>s.emit(d,a));s.emit("ready",void 0);}function T(e){var a;if(!g())return;if(n){console.warn(u,"init() called twice \u2014 ignored");return}n=true,t=!!e.debug;let c=(a=e.environment)!=null?a:"production";O({protocolVersion:1,sdkVersion:m,tagId:e.tagId,environment:c,debug:t});let d=I();d.length&&!d.includes(e.tagId)&&console.warn(u,`using Knock tag ${d} already on the page`),window.Knock?S():(window.addEventListener("knock:ready",S,{once:true}),x(R(c,e.tagId,e.scriptUrl))),t&&console.log(u,"initialized",window.__KNOCK_SDK__);}let w={};for(let e of ["show","hide","open","close"])w[e]=()=>f({path:`widget.${e}`,args:[]});return {init:T,identify(e){i=e.email,f({path:"identify",args:[e]});},track(e,c){f({path:"track",args:[e,c]});},modal:{open:(e={})=>f({path:"modal.open",args:[h(e)]}),close:()=>f({path:"modal.close",args:[]})},scheduling:{load(e){if(!g())return {open(){},close(){},status:"loading"};let c=h(e),d=p();if(d)return d.scheduling.load(c);let a=E();return v({path:"scheduling.load",args:[c],handle:a}),a}},widget:w,on(e,c){if(!g())return ()=>{};if(e!=="ready"||!o)return s.on(e,c);let d=true;return queueMicrotask(()=>d&&c(void 0)),()=>{d=false;}},get ready(){return o},get version(){return m},get surface(){return r}}}var C=V(),D=C,P=new Proxy({},{get:(n,o)=>o==="__knockai"?true:Reflect.get(D,o)}),J=P;function Y(n){D=n!=null?n:C;}
2
+ exports.VERSION=m;exports.__setKnockForTesting=Y;exports.createKnock=V;exports.default=J;exports.knock=P;//# sourceMappingURL=index.cjs.map
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/emitter.ts","../src/core/bridge.ts","../src/core/env.ts","../src/core/loader.ts","../src/core/version.ts","../src/core/index.ts"],"names":["Emitter","event","handler","listener","set","payload","LOG_PREFIX","createDeferredSchedulingHandle","real","pending","handle","resolve","runtime","path","head","tail","self","applyCommand","command","debug","args","fn","result","TAG_BUILD_PATH","tagBuildPath","environment","RUNTIME_SCRIPT_ID","TAG_SRC","hasRuntimeScript","s","bootedTagIds","_a","_b","i","buildScriptUrl","tagId","scriptUrl","writeBootConfig","config","injectRuntimeScript","url","script","VERSION","MAX_PENDING_COMMANDS","BRIDGED_EVENTS","browser","createKnock","initialized","ready","lastEmail","surface","emitter","withEmail","options","send","rt","enqueue","onReady","error","init","tags","widget","method","traits","eventName","properties","resolved","live","realKnock","activeKnock","knock","_","key","core_default","__setKnockForTesting","sdk"],"mappings":"sEAGO,IAAMA,CAAAA,CAAN,KAAuC,CAAvC,WAAA,EAAA,CACL,IAAA,CAAiB,SAAW,IAAI,IAAA,CAEhC,EAAA,CAA6BC,CAAAA,CAAUC,CAAAA,CAAqD,CAC1F,IAAMC,CAAAA,CAAWD,CAAAA,CACbE,CAAAA,CAAM,IAAA,CAAK,QAAA,CAAS,GAAA,CAAIH,CAAK,CAAA,CACjC,OAAKG,CAAAA,GACHA,CAAAA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,CACZ,OAAOQ,CACT,CACF,CACF,CAEA,IAAMkB,CAAAA,CAAYtB,CAAAA,EAAY,CAC1BuB,CAAAA,CAAwBD,CAAAA,CAOfE,CAAAA,CAAkB,IAAI,KAAA,CAAM,EAAC,CAAe,CAEvD,GAAA,CAAK,CAACC,CAAAA,CAAGC,CAAAA,GAASA,IAAQ,WAAA,CAAc,IAAA,CAAO,OAAA,CAAQ,GAAA,CAAIH,CAAAA,CAAaG,CAAG,CAC7E,CAAC,CAAA,CAEMC,CAAAA,CAAQH,EAOR,SAASI,CAAAA,CAAqBC,CAAAA,CAAiC,CACpEN,CAAAA,CAAcM,CAAAA,EAAA,IAAA,CAAAA,CAAAA,CAAOP,EACvB","file":"index.cjs","sourcesContent":["type Listener = (payload: unknown) => void;\n\n/** Minimal typed pub/sub. One instance per KnockSDK instance; not exported publicly. */\nexport class Emitter<EventMap extends object> {\n private readonly handlers = new Map<keyof EventMap, Set<Listener>>();\n\n on<E extends keyof EventMap>(event: E, handler: (payload: EventMap[E]) => void): () => void {\n const listener = handler as Listener;\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n }\n\n emit<E extends keyof EventMap>(event: E, payload: EventMap[E]): void {\n const set = this.handlers.get(event);\n if (!set) return;\n for (const listener of set) listener(payload);\n }\n\n clear(): void {\n this.handlers.clear();\n }\n}\n","import type { KnockRuntime, KnockSchedulingHandle, KnockSchedulingLoadOptions } from './types.js';\nimport type { DeferredSchedulingHandle, QueuedCommand } from './queue.js';\n\nconst LOG_PREFIX = '[knockai]';\n\n/** Returned synchronously from `scheduling.load()` before the runtime exists. */\nexport function createDeferredSchedulingHandle(): DeferredSchedulingHandle {\n let real: KnockSchedulingHandle | undefined;\n let pending: 'open' | 'close' | undefined;\n\n return {\n attach(handle) {\n real = handle;\n if (pending) handle[pending]();\n },\n open() {\n real ? real.open() : (pending = 'open');\n },\n close() {\n real ? real.close() : (pending = 'close');\n },\n get status() {\n return real ? real.status : 'loading';\n },\n };\n}\n\nfunction resolve(runtime: KnockRuntime, path: string): { fn: unknown; self: unknown } {\n const [head, tail] = path.split('.');\n const self = tail ? Reflect.get(runtime, head!) : runtime;\n return { self, fn: self ? Reflect.get(self as object, tail ?? head!) : undefined };\n}\n\n/** Applies one queued (or live) command against the loaded runtime. */\nexport function applyCommand(runtime: KnockRuntime, command: QueuedCommand, debug: boolean): void {\n const { path, args } = command;\n const { fn, self } = resolve(runtime, path);\n\n if (typeof fn === 'function') {\n const result = fn.apply(self, args) as KnockSchedulingHandle;\n if (command.handle) command.handle.attach(result);\n return;\n }\n // No dedicated modal in this runtime build — scheduling.load(...).open() is the fallback.\n if (path === 'modal.open') {\n runtime.scheduling.load(args[0] as KnockSchedulingLoadOptions).open();\n return;\n }\n if (debug) console.warn(LOG_PREFIX, `no runtime ${path} — ignored`);\n}\n","import type { KnockEnvironment } from './types.js';\n\n/** Path each environment's tag builds are served from. */\nconst TAG_BUILD_PATH: Record<KnockEnvironment, string> = {\n production: 'knock-tag-build/prod',\n staging: 'knock-tag-build-stg/prod',\n development: 'knock-tag-build/dev',\n};\n\nexport function tagBuildPath(environment: KnockEnvironment): string {\n return TAG_BUILD_PATH[environment];\n}\n","import type { KnockEnvironment, KnockSdkBootConfig } from './types.js';\nimport { tagBuildPath } from './env.js';\n\nconst RUNTIME_SCRIPT_ID = 'knockai-runtime';\n/** A Knock tag the vendor already pasted: hosted snippet (js.knock-ai.com), CDN build, or self-hosted. */\nconst TAG_SRC = /knock-ai\\.com\\/|knock-tag/;\n\n/** True when a Knock runtime <script> is already in the DOM (booted or still loading). */\nexport function hasRuntimeScript(): boolean {\n return [...document.scripts].some((s) => s.id === RUNTIME_SCRIPT_ID || TAG_SRC.test(s.src));\n}\n\n/** tagIds of Knock tags that already booted on this page (the Knock tag's own duplicate guard). */\nexport function bootedTagIds(): string[] {\n return [...(window.__knockTagInstances?.values() ?? [])].map((i) => i.tagId);\n}\n\nexport function buildScriptUrl(\n environment: KnockEnvironment,\n tagId: string,\n scriptUrl?: string,\n): string {\n if (scriptUrl) return scriptUrl;\n return `https://storage.googleapis.com/${tagBuildPath(environment)}/${tagId}/latest/index.js`;\n}\n\n/** Informational; the current Knock tag doesn't read it. */\nexport function writeBootConfig(config: KnockSdkBootConfig): void {\n if (typeof window === 'undefined') return;\n window.__KNOCK_SDK__ = config;\n}\n\nexport function injectRuntimeScript(url: string): void {\n if (typeof document === 'undefined' || hasRuntimeScript()) return;\n const script = document.createElement('script');\n script.id = RUNTIME_SCRIPT_ID;\n script.async = true;\n script.src = url;\n document.head.appendChild(script);\n}\n","// Must equal package.json's \"version\" — bump both together; version.test.ts fails CI otherwise.\nexport const VERSION = '0.1.2';\n","import type {\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockRuntime,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockTagSurface,\n} from './types.js';\nimport { Emitter } from './emitter.js';\nimport type { QueuedCommand } from './queue.js';\nimport { applyCommand, createDeferredSchedulingHandle } from './bridge.js';\nimport { bootedTagIds, buildScriptUrl, injectRuntimeScript, writeBootConfig } from './loader.js';\nimport { VERSION } from './version.js';\n\nexport type {\n KnockEnvironment,\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockRuntime,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockSchedulingStatus,\n KnockSchedulingStatusChange,\n KnockSdkBootConfig,\n KnockTagSurface,\n} from './types.js';\nexport { VERSION } from './version.js';\n\nconst LOG_PREFIX = '[knockai]';\n/** Calls held before the runtime is ready; past this the page is calling faster than Knock can load. */\nconst MAX_PENDING_COMMANDS = 1000;\nconst BRIDGED_EVENTS = ['modal:open', 'modal:close', 'widget:open', 'widget:close', 'error'] as const;\ntype WidgetMethod = 'show' | 'hide' | 'open' | 'close';\n\nfunction browser(): boolean {\n return typeof window !== 'undefined';\n}\n\n/**\n * Builds one independent KnockSDK instance: its own queue, emitter and ready\n * state. Use this in tests, or when a page legitimately needs two instances;\n * everyday code should use the `knock` singleton below instead.\n */\nexport function createKnock(): KnockSDK {\n let initialized = false;\n let ready = false;\n let debug = false;\n let lastEmail: string | undefined;\n let surface: KnockTagSurface | undefined;\n const emitter = new Emitter<KnockEventMap>();\n const pending: QueuedCommand[] = [];\n\n function runtime(): KnockRuntime | undefined {\n return ready && browser() ? window.Knock : undefined;\n }\n\n // Adds `email` from the last identify() when the caller didn't pass one.\n function withEmail<T extends KnockModalOpenOptions>(options: T): T {\n return options.email || !lastEmail ? options : { ...options, email: lastEmail };\n }\n\n function send(command: QueuedCommand): void {\n if (!browser()) return;\n const rt = runtime();\n if (rt) applyCommand(rt, command, debug);\n else enqueue(command);\n }\n\n function enqueue(command: QueuedCommand): void {\n if (pending.length < MAX_PENDING_COMMANDS) pending.push(command);\n else if (debug) console.warn(LOG_PREFIX, `${MAX_PENDING_COMMANDS} calls queued before Knock loaded — ${command.path} dropped`);\n }\n\n function onReady(): void {\n if (ready) return;\n ready = true;\n const rt = runtime();\n if (!rt) {\n if (debug) console.warn(LOG_PREFIX, 'ready without window.Knock');\n return;\n }\n if (rt.surface === 'website' || rt.surface === 'product') surface = rt.surface;\n for (const command of pending.splice(0)) {\n try {\n applyCommand(rt, command, debug);\n } catch (error) {\n if (debug) console.warn(LOG_PREFIX, command.path, error);\n }\n }\n for (const event of BRIDGED_EVENTS) rt.on?.(event, (payload) => emitter.emit(event, payload));\n emitter.emit('ready', undefined);\n }\n\n function init(options: KnockInitOptions): void {\n if (!browser()) return;\n if (initialized) {\n console.warn(LOG_PREFIX, 'init() called twice — ignored');\n return;\n }\n initialized = true;\n debug = !!options.debug;\n const environment = options.environment ?? 'production';\n writeBootConfig({\n protocolVersion: 1,\n sdkVersion: VERSION,\n tagId: options.tagId,\n environment,\n debug,\n });\n // Never load a second runtime: adopt a tag the vendor already pasted. If it booted first its\n // knock:ready is gone, so attach now; if it's still loading, injectRuntimeScript sees its <script>.\n const tags = bootedTagIds();\n if (tags.length && !tags.includes(options.tagId)) console.warn(LOG_PREFIX, `using Knock tag ${tags} already on the page`);\n if (window.Knock) onReady();\n else {\n window.addEventListener('knock:ready', onReady, { once: true });\n injectRuntimeScript(buildScriptUrl(environment, options.tagId, options.scriptUrl));\n }\n if (debug) console.log(LOG_PREFIX, 'initialized', window.__KNOCK_SDK__);\n }\n\n const widget = {} as Record<WidgetMethod, () => void>;\n for (const method of ['show', 'hide', 'open', 'close'] as const) {\n widget[method] = () => send({ path: `widget.${method}`, args: [] });\n }\n\n return {\n init,\n identify(traits: KnockIdentifyTraits): void {\n lastEmail = traits.email;\n send({ path: 'identify', args: [traits] });\n },\n track(eventName: string, properties?: Record<string, KnockFieldValue>): void {\n send({ path: 'track', args: [eventName, properties] });\n },\n modal: {\n open: (options: KnockModalOpenOptions = {}) => send({ path: 'modal.open', args: [withEmail(options)] }),\n close: () => send({ path: 'modal.close', args: [] }),\n },\n scheduling: {\n load(options: KnockSchedulingLoadOptions): KnockSchedulingHandle {\n if (!browser()) return { open() {}, close() {}, status: 'loading' };\n const resolved = withEmail(options);\n const rt = runtime();\n if (rt) return rt.scheduling.load(resolved);\n const handle = createDeferredSchedulingHandle();\n enqueue({ path: 'scheduling.load', args: [resolved], handle });\n return handle;\n },\n },\n widget,\n on<E extends KnockEventName>(event: E, handler: (payload: KnockEventMap[E]) => void): () => void {\n if (!browser()) return () => {};\n if (event !== 'ready' || !ready) return emitter.on(event, handler);\n // `ready` already fired: a late subscriber still gets it, once, unless it unsubscribes first.\n let live = true;\n queueMicrotask(() => live && handler(undefined as KnockEventMap[E]));\n return () => void (live = false);\n },\n get ready() {\n return ready;\n },\n get version() {\n return VERSION;\n },\n get surface() {\n return surface;\n },\n };\n}\n\nconst realKnock = createKnock();\nlet activeKnock: KnockSDK = realKnock;\n\n/**\n * The shared `knock` instance. Property reads resolve through `activeKnock` at\n * access time, so `__setKnockForTesting` can redirect every framework binding\n * without any of them re-importing anything.\n */\nexport const knock: KnockSDK = new Proxy({} as KnockSDK, {\n // `__knockai` marks the facade so the CDN stub never mistakes it for a host page's own `window.knock`.\n get: (_, key) => (key === '__knockai' ? true : Reflect.get(activeKnock, key)),\n});\n\nexport default knock;\n\n/**\n * Test-only hook: redirects the `knock` singleton to `sdk` (e.g. a\n * `createKnockMock()` from `@knock-ai/sdk/testing`), or back to the real SDK when\n * called with `undefined`.\n */\nexport function __setKnockForTesting(sdk: KnockSDK | undefined): void {\n activeKnock = sdk ?? realKnock;\n}\n"]}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ var k=class{constructor(){this.handlers=new Map;}on(o,t){let i=t,r=this.handlers.get(o);return r||(r=new Set,this.handlers.set(o,r)),r.add(i),()=>{r.delete(i);}}emit(o,t){let i=this.handlers.get(o);if(i)for(let r of i)r(t);}clear(){this.handlers.clear();}};var b="[knockai]";function E(){let n,o;return {attach(t){n=t,o&&t[o]();},open(){n?n.open():o="open";},close(){n?n.close():o="close";},get status(){return n?n.status:"loading"}}}function N(n,o){let[t,i]=o.split("."),r=i?Reflect.get(n,t):n;return {self:r,fn:r?Reflect.get(r,i!=null?i:t):void 0}}function K(n,o,t){let{path:i,args:r}=o,{fn:s,self:l}=N(n,i);if(typeof s=="function"){let p=s.apply(l,r);o.handle&&o.handle.attach(p);return}if(i==="modal.open"){n.scheduling.load(r[0]).open();return}t&&console.warn(b,`no runtime ${i} \u2014 ignored`);}var j={production:"knock-tag-build/prod",staging:"knock-tag-build-stg/prod",development:"knock-tag-build/dev"};function y(n){return j[n]}var _="knockai-runtime",L=/knock-ai\.com\/|knock-tag/;function H(){return [...document.scripts].some(n=>n.id===_||L.test(n.src))}function I(){var n,o;return [...(o=(n=window.__knockTagInstances)==null?void 0:n.values())!=null?o:[]].map(t=>t.tagId)}function R(n,o,t){return t||`https://storage.googleapis.com/${y(n)}/${o}/latest/index.js`}function O(n){typeof window!="undefined"&&(window.__KNOCK_SDK__=n);}function x(n){if(typeof document=="undefined"||H())return;let o=document.createElement("script");o.id=_,o.async=true,o.src=n,document.head.appendChild(o);}var m="0.1.2";var u="[knockai]",M=1e3,B=["modal:open","modal:close","widget:open","widget:close","error"];function g(){return typeof window!="undefined"}function V(){let n=false,o=false,t=false,i,r,s=new k,l=[];function p(){return o&&g()?window.Knock:void 0}function h(e){return e.email||!i?e:{...e,email:i}}function f(e){if(!g())return;let c=p();c?K(c,e,t):v(e);}function v(e){l.length<M?l.push(e):t&&console.warn(u,`${M} calls queued before Knock loaded \u2014 ${e.path} dropped`);}function S(){var c;if(o)return;o=true;let e=p();if(!e){t&&console.warn(u,"ready without window.Knock");return}(e.surface==="website"||e.surface==="product")&&(r=e.surface);for(let d of l.splice(0))try{K(e,d,t);}catch(a){t&&console.warn(u,d.path,a);}for(let d of B)(c=e.on)==null||c.call(e,d,a=>s.emit(d,a));s.emit("ready",void 0);}function T(e){var a;if(!g())return;if(n){console.warn(u,"init() called twice \u2014 ignored");return}n=true,t=!!e.debug;let c=(a=e.environment)!=null?a:"production";O({protocolVersion:1,sdkVersion:m,tagId:e.tagId,environment:c,debug:t});let d=I();d.length&&!d.includes(e.tagId)&&console.warn(u,`using Knock tag ${d} already on the page`),window.Knock?S():(window.addEventListener("knock:ready",S,{once:true}),x(R(c,e.tagId,e.scriptUrl))),t&&console.log(u,"initialized",window.__KNOCK_SDK__);}let w={};for(let e of ["show","hide","open","close"])w[e]=()=>f({path:`widget.${e}`,args:[]});return {init:T,identify(e){i=e.email,f({path:"identify",args:[e]});},track(e,c){f({path:"track",args:[e,c]});},modal:{open:(e={})=>f({path:"modal.open",args:[h(e)]}),close:()=>f({path:"modal.close",args:[]})},scheduling:{load(e){if(!g())return {open(){},close(){},status:"loading"};let c=h(e),d=p();if(d)return d.scheduling.load(c);let a=E();return v({path:"scheduling.load",args:[c],handle:a}),a}},widget:w,on(e,c){if(!g())return ()=>{};if(e!=="ready"||!o)return s.on(e,c);let d=true;return queueMicrotask(()=>d&&c(void 0)),()=>{d=false;}},get ready(){return o},get version(){return m},get surface(){return r}}}var C=V(),D=C,P=new Proxy({},{get:(n,o)=>o==="__knockai"?true:Reflect.get(D,o)}),J=P;function Y(n){D=n!=null?n:C;}
2
+ export{m as VERSION,Y as __setKnockForTesting,V as createKnock,J as default,P as knock};//# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/emitter.ts","../src/core/bridge.ts","../src/core/env.ts","../src/core/loader.ts","../src/core/version.ts","../src/core/index.ts"],"names":["Emitter","event","handler","listener","set","payload","LOG_PREFIX","createDeferredSchedulingHandle","real","pending","handle","resolve","runtime","path","head","tail","self","applyCommand","command","debug","args","fn","result","TAG_BUILD_PATH","tagBuildPath","environment","RUNTIME_SCRIPT_ID","TAG_SRC","hasRuntimeScript","s","bootedTagIds","_a","_b","i","buildScriptUrl","tagId","scriptUrl","writeBootConfig","config","injectRuntimeScript","url","script","VERSION","MAX_PENDING_COMMANDS","BRIDGED_EVENTS","browser","createKnock","initialized","ready","lastEmail","surface","emitter","withEmail","options","send","rt","enqueue","onReady","error","init","tags","widget","method","traits","eventName","properties","resolved","live","realKnock","activeKnock","knock","_","key","core_default","__setKnockForTesting","sdk"],"mappings":"AAGO,IAAMA,CAAAA,CAAN,KAAuC,CAAvC,WAAA,EAAA,CACL,IAAA,CAAiB,SAAW,IAAI,IAAA,CAEhC,EAAA,CAA6BC,CAAAA,CAAUC,CAAAA,CAAqD,CAC1F,IAAMC,CAAAA,CAAWD,CAAAA,CACbE,CAAAA,CAAM,IAAA,CAAK,QAAA,CAAS,GAAA,CAAIH,CAAK,CAAA,CACjC,OAAKG,CAAAA,GACHA,CAAAA,CAAM,IAAI,GAAA,CACV,KAAK,QAAA,CAAS,GAAA,CAAIH,CAAAA,CAAOG,CAAG,CAAA,CAAA,CAE9BA,C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,CAAAA,CAOfE,CAAAA,CAAkB,IAAI,KAAA,CAAM,EAAC,CAAe,CAEvD,GAAA,CAAK,CAACC,CAAAA,CAAGC,CAAAA,GAASA,IAAQ,WAAA,CAAc,IAAA,CAAO,OAAA,CAAQ,GAAA,CAAIH,CAAAA,CAAaG,CAAG,CAC7E,CAAC,CAAA,CAEMC,CAAAA,CAAQH,EAOR,SAASI,CAAAA,CAAqBC,CAAAA,CAAiC,CACpEN,CAAAA,CAAcM,CAAAA,EAAA,IAAA,CAAAA,CAAAA,CAAOP,EACvB","file":"index.js","sourcesContent":["type Listener = (payload: unknown) => void;\n\n/** Minimal typed pub/sub. One instance per KnockSDK instance; not exported publicly. */\nexport class Emitter<EventMap extends object> {\n private readonly handlers = new Map<keyof EventMap, Set<Listener>>();\n\n on<E extends keyof EventMap>(event: E, handler: (payload: EventMap[E]) => void): () => void {\n const listener = handler as Listener;\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n }\n\n emit<E extends keyof EventMap>(event: E, payload: EventMap[E]): void {\n const set = this.handlers.get(event);\n if (!set) return;\n for (const listener of set) listener(payload);\n }\n\n clear(): void {\n this.handlers.clear();\n }\n}\n","import type { KnockRuntime, KnockSchedulingHandle, KnockSchedulingLoadOptions } from './types.js';\nimport type { DeferredSchedulingHandle, QueuedCommand } from './queue.js';\n\nconst LOG_PREFIX = '[knockai]';\n\n/** Returned synchronously from `scheduling.load()` before the runtime exists. */\nexport function createDeferredSchedulingHandle(): DeferredSchedulingHandle {\n let real: KnockSchedulingHandle | undefined;\n let pending: 'open' | 'close' | undefined;\n\n return {\n attach(handle) {\n real = handle;\n if (pending) handle[pending]();\n },\n open() {\n real ? real.open() : (pending = 'open');\n },\n close() {\n real ? real.close() : (pending = 'close');\n },\n get status() {\n return real ? real.status : 'loading';\n },\n };\n}\n\nfunction resolve(runtime: KnockRuntime, path: string): { fn: unknown; self: unknown } {\n const [head, tail] = path.split('.');\n const self = tail ? Reflect.get(runtime, head!) : runtime;\n return { self, fn: self ? Reflect.get(self as object, tail ?? head!) : undefined };\n}\n\n/** Applies one queued (or live) command against the loaded runtime. */\nexport function applyCommand(runtime: KnockRuntime, command: QueuedCommand, debug: boolean): void {\n const { path, args } = command;\n const { fn, self } = resolve(runtime, path);\n\n if (typeof fn === 'function') {\n const result = fn.apply(self, args) as KnockSchedulingHandle;\n if (command.handle) command.handle.attach(result);\n return;\n }\n // No dedicated modal in this runtime build — scheduling.load(...).open() is the fallback.\n if (path === 'modal.open') {\n runtime.scheduling.load(args[0] as KnockSchedulingLoadOptions).open();\n return;\n }\n if (debug) console.warn(LOG_PREFIX, `no runtime ${path} — ignored`);\n}\n","import type { KnockEnvironment } from './types.js';\n\n/** Path each environment's tag builds are served from. */\nconst TAG_BUILD_PATH: Record<KnockEnvironment, string> = {\n production: 'knock-tag-build/prod',\n staging: 'knock-tag-build-stg/prod',\n development: 'knock-tag-build/dev',\n};\n\nexport function tagBuildPath(environment: KnockEnvironment): string {\n return TAG_BUILD_PATH[environment];\n}\n","import type { KnockEnvironment, KnockSdkBootConfig } from './types.js';\nimport { tagBuildPath } from './env.js';\n\nconst RUNTIME_SCRIPT_ID = 'knockai-runtime';\n/** A Knock tag the vendor already pasted: hosted snippet (js.knock-ai.com), CDN build, or self-hosted. */\nconst TAG_SRC = /knock-ai\\.com\\/|knock-tag/;\n\n/** True when a Knock runtime <script> is already in the DOM (booted or still loading). */\nexport function hasRuntimeScript(): boolean {\n return [...document.scripts].some((s) => s.id === RUNTIME_SCRIPT_ID || TAG_SRC.test(s.src));\n}\n\n/** tagIds of Knock tags that already booted on this page (the Knock tag's own duplicate guard). */\nexport function bootedTagIds(): string[] {\n return [...(window.__knockTagInstances?.values() ?? [])].map((i) => i.tagId);\n}\n\nexport function buildScriptUrl(\n environment: KnockEnvironment,\n tagId: string,\n scriptUrl?: string,\n): string {\n if (scriptUrl) return scriptUrl;\n return `https://storage.googleapis.com/${tagBuildPath(environment)}/${tagId}/latest/index.js`;\n}\n\n/** Informational; the current Knock tag doesn't read it. */\nexport function writeBootConfig(config: KnockSdkBootConfig): void {\n if (typeof window === 'undefined') return;\n window.__KNOCK_SDK__ = config;\n}\n\nexport function injectRuntimeScript(url: string): void {\n if (typeof document === 'undefined' || hasRuntimeScript()) return;\n const script = document.createElement('script');\n script.id = RUNTIME_SCRIPT_ID;\n script.async = true;\n script.src = url;\n document.head.appendChild(script);\n}\n","// Must equal package.json's \"version\" — bump both together; version.test.ts fails CI otherwise.\nexport const VERSION = '0.1.2';\n","import type {\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockRuntime,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockTagSurface,\n} from './types.js';\nimport { Emitter } from './emitter.js';\nimport type { QueuedCommand } from './queue.js';\nimport { applyCommand, createDeferredSchedulingHandle } from './bridge.js';\nimport { bootedTagIds, buildScriptUrl, injectRuntimeScript, writeBootConfig } from './loader.js';\nimport { VERSION } from './version.js';\n\nexport type {\n KnockEnvironment,\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockRuntime,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockSchedulingStatus,\n KnockSchedulingStatusChange,\n KnockSdkBootConfig,\n KnockTagSurface,\n} from './types.js';\nexport { VERSION } from './version.js';\n\nconst LOG_PREFIX = '[knockai]';\n/** Calls held before the runtime is ready; past this the page is calling faster than Knock can load. */\nconst MAX_PENDING_COMMANDS = 1000;\nconst BRIDGED_EVENTS = ['modal:open', 'modal:close', 'widget:open', 'widget:close', 'error'] as const;\ntype WidgetMethod = 'show' | 'hide' | 'open' | 'close';\n\nfunction browser(): boolean {\n return typeof window !== 'undefined';\n}\n\n/**\n * Builds one independent KnockSDK instance: its own queue, emitter and ready\n * state. Use this in tests, or when a page legitimately needs two instances;\n * everyday code should use the `knock` singleton below instead.\n */\nexport function createKnock(): KnockSDK {\n let initialized = false;\n let ready = false;\n let debug = false;\n let lastEmail: string | undefined;\n let surface: KnockTagSurface | undefined;\n const emitter = new Emitter<KnockEventMap>();\n const pending: QueuedCommand[] = [];\n\n function runtime(): KnockRuntime | undefined {\n return ready && browser() ? window.Knock : undefined;\n }\n\n // Adds `email` from the last identify() when the caller didn't pass one.\n function withEmail<T extends KnockModalOpenOptions>(options: T): T {\n return options.email || !lastEmail ? options : { ...options, email: lastEmail };\n }\n\n function send(command: QueuedCommand): void {\n if (!browser()) return;\n const rt = runtime();\n if (rt) applyCommand(rt, command, debug);\n else enqueue(command);\n }\n\n function enqueue(command: QueuedCommand): void {\n if (pending.length < MAX_PENDING_COMMANDS) pending.push(command);\n else if (debug) console.warn(LOG_PREFIX, `${MAX_PENDING_COMMANDS} calls queued before Knock loaded — ${command.path} dropped`);\n }\n\n function onReady(): void {\n if (ready) return;\n ready = true;\n const rt = runtime();\n if (!rt) {\n if (debug) console.warn(LOG_PREFIX, 'ready without window.Knock');\n return;\n }\n if (rt.surface === 'website' || rt.surface === 'product') surface = rt.surface;\n for (const command of pending.splice(0)) {\n try {\n applyCommand(rt, command, debug);\n } catch (error) {\n if (debug) console.warn(LOG_PREFIX, command.path, error);\n }\n }\n for (const event of BRIDGED_EVENTS) rt.on?.(event, (payload) => emitter.emit(event, payload));\n emitter.emit('ready', undefined);\n }\n\n function init(options: KnockInitOptions): void {\n if (!browser()) return;\n if (initialized) {\n console.warn(LOG_PREFIX, 'init() called twice — ignored');\n return;\n }\n initialized = true;\n debug = !!options.debug;\n const environment = options.environment ?? 'production';\n writeBootConfig({\n protocolVersion: 1,\n sdkVersion: VERSION,\n tagId: options.tagId,\n environment,\n debug,\n });\n // Never load a second runtime: adopt a tag the vendor already pasted. If it booted first its\n // knock:ready is gone, so attach now; if it's still loading, injectRuntimeScript sees its <script>.\n const tags = bootedTagIds();\n if (tags.length && !tags.includes(options.tagId)) console.warn(LOG_PREFIX, `using Knock tag ${tags} already on the page`);\n if (window.Knock) onReady();\n else {\n window.addEventListener('knock:ready', onReady, { once: true });\n injectRuntimeScript(buildScriptUrl(environment, options.tagId, options.scriptUrl));\n }\n if (debug) console.log(LOG_PREFIX, 'initialized', window.__KNOCK_SDK__);\n }\n\n const widget = {} as Record<WidgetMethod, () => void>;\n for (const method of ['show', 'hide', 'open', 'close'] as const) {\n widget[method] = () => send({ path: `widget.${method}`, args: [] });\n }\n\n return {\n init,\n identify(traits: KnockIdentifyTraits): void {\n lastEmail = traits.email;\n send({ path: 'identify', args: [traits] });\n },\n track(eventName: string, properties?: Record<string, KnockFieldValue>): void {\n send({ path: 'track', args: [eventName, properties] });\n },\n modal: {\n open: (options: KnockModalOpenOptions = {}) => send({ path: 'modal.open', args: [withEmail(options)] }),\n close: () => send({ path: 'modal.close', args: [] }),\n },\n scheduling: {\n load(options: KnockSchedulingLoadOptions): KnockSchedulingHandle {\n if (!browser()) return { open() {}, close() {}, status: 'loading' };\n const resolved = withEmail(options);\n const rt = runtime();\n if (rt) return rt.scheduling.load(resolved);\n const handle = createDeferredSchedulingHandle();\n enqueue({ path: 'scheduling.load', args: [resolved], handle });\n return handle;\n },\n },\n widget,\n on<E extends KnockEventName>(event: E, handler: (payload: KnockEventMap[E]) => void): () => void {\n if (!browser()) return () => {};\n if (event !== 'ready' || !ready) return emitter.on(event, handler);\n // `ready` already fired: a late subscriber still gets it, once, unless it unsubscribes first.\n let live = true;\n queueMicrotask(() => live && handler(undefined as KnockEventMap[E]));\n return () => void (live = false);\n },\n get ready() {\n return ready;\n },\n get version() {\n return VERSION;\n },\n get surface() {\n return surface;\n },\n };\n}\n\nconst realKnock = createKnock();\nlet activeKnock: KnockSDK = realKnock;\n\n/**\n * The shared `knock` instance. Property reads resolve through `activeKnock` at\n * access time, so `__setKnockForTesting` can redirect every framework binding\n * without any of them re-importing anything.\n */\nexport const knock: KnockSDK = new Proxy({} as KnockSDK, {\n // `__knockai` marks the facade so the CDN stub never mistakes it for a host page's own `window.knock`.\n get: (_, key) => (key === '__knockai' ? true : Reflect.get(activeKnock, key)),\n});\n\nexport default knock;\n\n/**\n * Test-only hook: redirects the `knock` singleton to `sdk` (e.g. a\n * `createKnockMock()` from `@knock-ai/sdk/testing`), or back to the real SDK when\n * called with `undefined`.\n */\nexport function __setKnockForTesting(sdk: KnockSDK | undefined): void {\n activeKnock = sdk ?? realKnock;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ (function(){'use strict';var K=class{constructor(){this.handlers=new Map;}on(e,t){let r=t,i=this.handlers.get(e);return i||(i=new Set,this.handlers.set(e,i)),i.add(r),()=>{i.delete(r);}}emit(e,t){let r=this.handlers.get(e);if(r)for(let i of r)i(t);}clear(){this.handlers.clear();}};var N="[knockai]";function b(){let n,e;return {attach(t){n=t,e&&t[e]();},open(){n?n.open():e="open";},close(){n?n.close():e="close";},get status(){return n?n.status:"loading"}}}function L(n,e){let[t,r]=e.split("."),i=r?Reflect.get(n,t):n;return {self:i,fn:i?Reflect.get(i,r!=null?r:t):void 0}}function m(n,e,t){let{path:r,args:i}=e,{fn:a,self:u}=L(n,r);if(typeof a=="function"){let l=a.apply(u,i);e.handle&&e.handle.attach(l);return}if(r==="modal.open"){n.scheduling.load(i[0]).open();return}t&&console.warn(N,`no runtime ${r} \u2014 ignored`);}var H={production:"knock-tag-build/prod",staging:"knock-tag-build-stg/prod",development:"knock-tag-build/dev"};function _(n){return H[n]}var x="knockai-runtime",q=/knock-ai\.com\/|knock-tag/;function B(){return [...document.scripts].some(n=>n.id===x||q.test(n.src))}function R(){var n,e;return [...(e=(n=window.__knockTagInstances)==null?void 0:n.values())!=null?e:[]].map(t=>t.tagId)}function C(n,e,t){return t||`https://storage.googleapis.com/${_(n)}/${e}/latest/index.js`}function I(n){typeof window!="undefined"&&(window.__KNOCK_SDK__=n);}function O(n){if(typeof document=="undefined"||B())return;let e=document.createElement("script");e.id=x,e.async=true,e.src=n,document.head.appendChild(e);}var w="0.1.2";var f="[knockai]",M=1e3,V=["modal:open","modal:close","widget:open","widget:close","error"];function p(){return typeof window!="undefined"}function G(){let n=false,e=false,t=false,r,i,a=new K,u=[];function l(){return e&&p()?window.Knock:void 0}function S(o){return o.email||!r?o:{...o,email:r}}function k(o){if(!p())return;let c=l();c?m(c,o,t):y(o);}function y(o){u.length<M?u.push(o):t&&console.warn(f,`${M} calls queued before Knock loaded \u2014 ${o.path} dropped`);}function v(){var c;if(e)return;e=true;let o=l();if(!o){t&&console.warn(f,"ready without window.Knock");return}(o.surface==="website"||o.surface==="product")&&(i=o.surface);for(let d of u.splice(0))try{m(o,d,t);}catch(s){t&&console.warn(f,d.path,s);}for(let d of V)(c=o.on)==null||c.call(o,d,s=>a.emit(d,s));a.emit("ready",void 0);}function j(o){var s;if(!p())return;if(n){console.warn(f,"init() called twice \u2014 ignored");return}n=true,t=!!o.debug;let c=(s=o.environment)!=null?s:"production";I({protocolVersion:1,sdkVersion:w,tagId:o.tagId,environment:c,debug:t});let d=R();d.length&&!d.includes(o.tagId)&&console.warn(f,`using Knock tag ${d} already on the page`),window.Knock?v():(window.addEventListener("knock:ready",v,{once:true}),O(C(c,o.tagId,o.scriptUrl))),t&&console.log(f,"initialized",window.__KNOCK_SDK__);}let E={};for(let o of ["show","hide","open","close"])E[o]=()=>k({path:`widget.${o}`,args:[]});return {init:j,identify(o){r=o.email,k({path:"identify",args:[o]});},track(o,c){k({path:"track",args:[o,c]});},modal:{open:(o={})=>k({path:"modal.open",args:[S(o)]}),close:()=>k({path:"modal.close",args:[]})},scheduling:{load(o){if(!p())return {open(){},close(){},status:"loading"};let c=S(o),d=l();if(d)return d.scheduling.load(c);let s=b();return y({path:"scheduling.load",args:[c],handle:s}),s}},widget:E,on(o,c){if(!p())return ()=>{};if(o!=="ready"||!e)return a.on(o,c);let d=true;return queueMicrotask(()=>d&&c(void 0)),()=>{d=false;}},get ready(){return e},get version(){return w},get surface(){return i}}}var P=G(),A=P,g=new Proxy({},{get:(n,e)=>e==="__knockai"?true:Reflect.get(A,e)});function h(n){return !!n&&Array.isArray(n.q)}function D(n){return !n||h(n)||n.__knockai===true}function $([n,e,t]){if(typeof n=="function")return n();let[r,i]=n.split("."),a=i?Reflect.get(g,r):g,u=Reflect.get(a,i!=null?i:r);if(typeof u!="function")return;let l=u.apply(a,e);t&&t(l);}function F(n){for(let e of n)try{$(e);}catch{}}var T;if(typeof window!="undefined"&&!((T=window.knockai)!=null&&T.__knockai)){let n=[window.knockai,window.knock].find(h),e=D(window.knock);window.knockai=g,e&&(window.knock=g),n&&F(n.q);}
2
+ return g;})();//# sourceMappingURL=knockai.iife.js.map
3
+ //# sourceMappingURL=knockai.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/emitter.ts","../src/core/bridge.ts","../src/core/env.ts","../src/core/loader.ts","../src/core/version.ts","../src/core/index.ts","../src/core/globals.ts","../src/core/iife.ts"],"names":["Emitter","event","handler","listener","set","payload","LOG_PREFIX","createDeferredSchedulingHandle","real","pending","handle","resolve","runtime","path","head","tail","self","applyCommand","command","debug","args","fn","result","TAG_BUILD_PATH","tagBuildPath","environment","RUNTIME_SCRIPT_ID","TAG_SRC","hasRuntimeScript","s","bootedTagIds","_a","_b","i","buildScriptUrl","tagId","scriptUrl","writeBootConfig","config","injectRuntimeScript","url","script","VERSION","MAX_PENDING_COMMANDS","BRIDGED_EVENTS","browser","createKnock","initialized","ready","lastEmail","surface","emitter","withEmail","options","send","rt","enqueue","onReady","error","init","tags","widget","method","traits","eventName","properties","resolved","live","realKnock","activeKnock","knock","_","key","isStub","value","isKnockGlobal","call","bind","target","replay","calls","queued","stub","ownsKnock"],"mappings":"yBAGO,IAAMA,CAAAA,CAAN,KAAuC,CAAvC,WAAA,EAAA,CACL,IAAA,CAAiB,QAAA,CAAW,IAAI,IAAA,CAEhC,EAAA,CAA6BC,CAAAA,CAAUC,CAAAA,CAAqD,CAC1F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,CAAAA,CAAMC,CAAI,CAAA,CAAIF,CAAAA,CAAK,KAAA,CAAM,GAAG,CAAA,CAC7BiE,CAAAA,CAAS/D,CAAAA,CAAO,OAAA,CAAQ,GAAA,CAAIuD,CAAAA,CAAOxD,CAAI,CAAA,CAAIwD,CAAAA,CAC3CjD,CAAAA,CAAK,OAAA,CAAQ,GAAA,CAAIyD,CAAAA,CAAkB/D,CAAAA,EAAA,IAAA,CAAAA,CAAAA,CAAQD,CAAI,CAAA,CACrD,GAAI,OAAOO,CAAAA,EAAO,UAAA,CAAY,OAC9B,IAAMC,CAAAA,CAAkBD,EAAG,KAAA,CAAMyD,CAAAA,CAAQ1D,CAAI,CAAA,CACzCyD,CAAAA,EAAMA,CAAAA,CAAKvD,CAAM,EACvB,CAEA,SAASyD,CAAAA,CAAOC,CAAAA,CAAyB,CACvC,IAAA,IAAWC,CAAAA,IAAUD,CAAAA,CACnB,GAAI,CACFJ,CAAAA,CAAKK,CAAM,EACb,CAAA,KAAQ,CAER,CAEJ,CA1BA,IAAAlD,CAAAA,CA6BA,GAAI,OAAO,MAAA,EAAW,WAAA,EAAe,EAAA,CAAEA,EAAA,MAAA,CAAO,OAAA,GAAP,IAAA,EAAAA,CAAAA,CAAqD,SAAA,CAAA,CAAW,CACrG,IAAMmD,CAAAA,CAAO,CAAC,MAAA,CAAO,OAAA,CAAS,MAAA,CAAO,KAAK,CAAA,CAAE,IAAA,CAAKT,CAAM,CAAA,CACjDU,CAAAA,CAAYR,CAAAA,CAAc,MAAA,CAAO,KAAK,CAAA,CAC5C,MAAA,CAAO,OAAA,CAAUL,CAAAA,CACba,CAAAA,GAAW,MAAA,CAAO,KAAA,CAAQb,CAAAA,CAAAA,CAC1BY,CAAAA,EAAMH,CAAAA,CAAOG,CAAAA,CAAK,CAAC,EACzB","file":"knockai.iife.js","sourcesContent":["type Listener = (payload: unknown) => void;\n\n/** Minimal typed pub/sub. One instance per KnockSDK instance; not exported publicly. */\nexport class Emitter<EventMap extends object> {\n private readonly handlers = new Map<keyof EventMap, Set<Listener>>();\n\n on<E extends keyof EventMap>(event: E, handler: (payload: EventMap[E]) => void): () => void {\n const listener = handler as Listener;\n let set = this.handlers.get(event);\n if (!set) {\n set = new Set();\n this.handlers.set(event, set);\n }\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n }\n\n emit<E extends keyof EventMap>(event: E, payload: EventMap[E]): void {\n const set = this.handlers.get(event);\n if (!set) return;\n for (const listener of set) listener(payload);\n }\n\n clear(): void {\n this.handlers.clear();\n }\n}\n","import type { KnockRuntime, KnockSchedulingHandle, KnockSchedulingLoadOptions } from './types.js';\nimport type { DeferredSchedulingHandle, QueuedCommand } from './queue.js';\n\nconst LOG_PREFIX = '[knockai]';\n\n/** Returned synchronously from `scheduling.load()` before the runtime exists. */\nexport function createDeferredSchedulingHandle(): DeferredSchedulingHandle {\n let real: KnockSchedulingHandle | undefined;\n let pending: 'open' | 'close' | undefined;\n\n return {\n attach(handle) {\n real = handle;\n if (pending) handle[pending]();\n },\n open() {\n real ? real.open() : (pending = 'open');\n },\n close() {\n real ? real.close() : (pending = 'close');\n },\n get status() {\n return real ? real.status : 'loading';\n },\n };\n}\n\nfunction resolve(runtime: KnockRuntime, path: string): { fn: unknown; self: unknown } {\n const [head, tail] = path.split('.');\n const self = tail ? Reflect.get(runtime, head!) : runtime;\n return { self, fn: self ? Reflect.get(self as object, tail ?? head!) : undefined };\n}\n\n/** Applies one queued (or live) command against the loaded runtime. */\nexport function applyCommand(runtime: KnockRuntime, command: QueuedCommand, debug: boolean): void {\n const { path, args } = command;\n const { fn, self } = resolve(runtime, path);\n\n if (typeof fn === 'function') {\n const result = fn.apply(self, args) as KnockSchedulingHandle;\n if (command.handle) command.handle.attach(result);\n return;\n }\n // No dedicated modal in this runtime build — scheduling.load(...).open() is the fallback.\n if (path === 'modal.open') {\n runtime.scheduling.load(args[0] as KnockSchedulingLoadOptions).open();\n return;\n }\n if (debug) console.warn(LOG_PREFIX, `no runtime ${path} — ignored`);\n}\n","import type { KnockEnvironment } from './types.js';\n\n/** Path each environment's tag builds are served from. */\nconst TAG_BUILD_PATH: Record<KnockEnvironment, string> = {\n production: 'knock-tag-build/prod',\n staging: 'knock-tag-build-stg/prod',\n development: 'knock-tag-build/dev',\n};\n\nexport function tagBuildPath(environment: KnockEnvironment): string {\n return TAG_BUILD_PATH[environment];\n}\n","import type { KnockEnvironment, KnockSdkBootConfig } from './types.js';\nimport { tagBuildPath } from './env.js';\n\nconst RUNTIME_SCRIPT_ID = 'knockai-runtime';\n/** A Knock tag the vendor already pasted: hosted snippet (js.knock-ai.com), CDN build, or self-hosted. */\nconst TAG_SRC = /knock-ai\\.com\\/|knock-tag/;\n\n/** True when a Knock runtime <script> is already in the DOM (booted or still loading). */\nexport function hasRuntimeScript(): boolean {\n return [...document.scripts].some((s) => s.id === RUNTIME_SCRIPT_ID || TAG_SRC.test(s.src));\n}\n\n/** tagIds of Knock tags that already booted on this page (the Knock tag's own duplicate guard). */\nexport function bootedTagIds(): string[] {\n return [...(window.__knockTagInstances?.values() ?? [])].map((i) => i.tagId);\n}\n\nexport function buildScriptUrl(\n environment: KnockEnvironment,\n tagId: string,\n scriptUrl?: string,\n): string {\n if (scriptUrl) return scriptUrl;\n return `https://storage.googleapis.com/${tagBuildPath(environment)}/${tagId}/latest/index.js`;\n}\n\n/** Informational; the current Knock tag doesn't read it. */\nexport function writeBootConfig(config: KnockSdkBootConfig): void {\n if (typeof window === 'undefined') return;\n window.__KNOCK_SDK__ = config;\n}\n\nexport function injectRuntimeScript(url: string): void {\n if (typeof document === 'undefined' || hasRuntimeScript()) return;\n const script = document.createElement('script');\n script.id = RUNTIME_SCRIPT_ID;\n script.async = true;\n script.src = url;\n document.head.appendChild(script);\n}\n","// Must equal package.json's \"version\" — bump both together; version.test.ts fails CI otherwise.\nexport const VERSION = '0.1.2';\n","import type {\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockRuntime,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockTagSurface,\n} from './types.js';\nimport { Emitter } from './emitter.js';\nimport type { QueuedCommand } from './queue.js';\nimport { applyCommand, createDeferredSchedulingHandle } from './bridge.js';\nimport { bootedTagIds, buildScriptUrl, injectRuntimeScript, writeBootConfig } from './loader.js';\nimport { VERSION } from './version.js';\n\nexport type {\n KnockEnvironment,\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockRuntime,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockSchedulingStatus,\n KnockSchedulingStatusChange,\n KnockSdkBootConfig,\n KnockTagSurface,\n} from './types.js';\nexport { VERSION } from './version.js';\n\nconst LOG_PREFIX = '[knockai]';\n/** Calls held before the runtime is ready; past this the page is calling faster than Knock can load. */\nconst MAX_PENDING_COMMANDS = 1000;\nconst BRIDGED_EVENTS = ['modal:open', 'modal:close', 'widget:open', 'widget:close', 'error'] as const;\ntype WidgetMethod = 'show' | 'hide' | 'open' | 'close';\n\nfunction browser(): boolean {\n return typeof window !== 'undefined';\n}\n\n/**\n * Builds one independent KnockSDK instance: its own queue, emitter and ready\n * state. Use this in tests, or when a page legitimately needs two instances;\n * everyday code should use the `knock` singleton below instead.\n */\nexport function createKnock(): KnockSDK {\n let initialized = false;\n let ready = false;\n let debug = false;\n let lastEmail: string | undefined;\n let surface: KnockTagSurface | undefined;\n const emitter = new Emitter<KnockEventMap>();\n const pending: QueuedCommand[] = [];\n\n function runtime(): KnockRuntime | undefined {\n return ready && browser() ? window.Knock : undefined;\n }\n\n // Adds `email` from the last identify() when the caller didn't pass one.\n function withEmail<T extends KnockModalOpenOptions>(options: T): T {\n return options.email || !lastEmail ? options : { ...options, email: lastEmail };\n }\n\n function send(command: QueuedCommand): void {\n if (!browser()) return;\n const rt = runtime();\n if (rt) applyCommand(rt, command, debug);\n else enqueue(command);\n }\n\n function enqueue(command: QueuedCommand): void {\n if (pending.length < MAX_PENDING_COMMANDS) pending.push(command);\n else if (debug) console.warn(LOG_PREFIX, `${MAX_PENDING_COMMANDS} calls queued before Knock loaded — ${command.path} dropped`);\n }\n\n function onReady(): void {\n if (ready) return;\n ready = true;\n const rt = runtime();\n if (!rt) {\n if (debug) console.warn(LOG_PREFIX, 'ready without window.Knock');\n return;\n }\n if (rt.surface === 'website' || rt.surface === 'product') surface = rt.surface;\n for (const command of pending.splice(0)) {\n try {\n applyCommand(rt, command, debug);\n } catch (error) {\n if (debug) console.warn(LOG_PREFIX, command.path, error);\n }\n }\n for (const event of BRIDGED_EVENTS) rt.on?.(event, (payload) => emitter.emit(event, payload));\n emitter.emit('ready', undefined);\n }\n\n function init(options: KnockInitOptions): void {\n if (!browser()) return;\n if (initialized) {\n console.warn(LOG_PREFIX, 'init() called twice — ignored');\n return;\n }\n initialized = true;\n debug = !!options.debug;\n const environment = options.environment ?? 'production';\n writeBootConfig({\n protocolVersion: 1,\n sdkVersion: VERSION,\n tagId: options.tagId,\n environment,\n debug,\n });\n // Never load a second runtime: adopt a tag the vendor already pasted. If it booted first its\n // knock:ready is gone, so attach now; if it's still loading, injectRuntimeScript sees its <script>.\n const tags = bootedTagIds();\n if (tags.length && !tags.includes(options.tagId)) console.warn(LOG_PREFIX, `using Knock tag ${tags} already on the page`);\n if (window.Knock) onReady();\n else {\n window.addEventListener('knock:ready', onReady, { once: true });\n injectRuntimeScript(buildScriptUrl(environment, options.tagId, options.scriptUrl));\n }\n if (debug) console.log(LOG_PREFIX, 'initialized', window.__KNOCK_SDK__);\n }\n\n const widget = {} as Record<WidgetMethod, () => void>;\n for (const method of ['show', 'hide', 'open', 'close'] as const) {\n widget[method] = () => send({ path: `widget.${method}`, args: [] });\n }\n\n return {\n init,\n identify(traits: KnockIdentifyTraits): void {\n lastEmail = traits.email;\n send({ path: 'identify', args: [traits] });\n },\n track(eventName: string, properties?: Record<string, KnockFieldValue>): void {\n send({ path: 'track', args: [eventName, properties] });\n },\n modal: {\n open: (options: KnockModalOpenOptions = {}) => send({ path: 'modal.open', args: [withEmail(options)] }),\n close: () => send({ path: 'modal.close', args: [] }),\n },\n scheduling: {\n load(options: KnockSchedulingLoadOptions): KnockSchedulingHandle {\n if (!browser()) return { open() {}, close() {}, status: 'loading' };\n const resolved = withEmail(options);\n const rt = runtime();\n if (rt) return rt.scheduling.load(resolved);\n const handle = createDeferredSchedulingHandle();\n enqueue({ path: 'scheduling.load', args: [resolved], handle });\n return handle;\n },\n },\n widget,\n on<E extends KnockEventName>(event: E, handler: (payload: KnockEventMap[E]) => void): () => void {\n if (!browser()) return () => {};\n if (event !== 'ready' || !ready) return emitter.on(event, handler);\n // `ready` already fired: a late subscriber still gets it, once, unless it unsubscribes first.\n let live = true;\n queueMicrotask(() => live && handler(undefined as KnockEventMap[E]));\n return () => void (live = false);\n },\n get ready() {\n return ready;\n },\n get version() {\n return VERSION;\n },\n get surface() {\n return surface;\n },\n };\n}\n\nconst realKnock = createKnock();\nlet activeKnock: KnockSDK = realKnock;\n\n/**\n * The shared `knock` instance. Property reads resolve through `activeKnock` at\n * access time, so `__setKnockForTesting` can redirect every framework binding\n * without any of them re-importing anything.\n */\nexport const knock: KnockSDK = new Proxy({} as KnockSDK, {\n // `__knockai` marks the facade so the CDN stub never mistakes it for a host page's own `window.knock`.\n get: (_, key) => (key === '__knockai' ? true : Reflect.get(activeKnock, key)),\n});\n\nexport default knock;\n\n/**\n * Test-only hook: redirects the `knock` singleton to `sdk` (e.g. a\n * `createKnockMock()` from `@knock-ai/sdk/testing`), or back to the real SDK when\n * called with `undefined`.\n */\nexport function __setKnockForTesting(sdk: KnockSDK | undefined): void {\n activeKnock = sdk ?? realKnock;\n}\n","/** Shared by the CDN stub and the IIFE facade. No side effects — importing it must never install anything. */\n\n/**\n * Replayed by the IIFE in order: `path` is called on the facade with `args` and `bind` gets its return value;\n * a function `path` (a handle op queued before load) is just called.\n */\nexport type StubCall = [path: string | (() => void), args: unknown[], bind?: (result: unknown) => void];\n\nexport interface KnockStub {\n q: StubCall[];\n [key: string]: unknown;\n}\n\ndeclare global {\n interface Window {\n /** The public global: `knock.identify(...)`. Left alone if the page already owns `window.knock`. */\n knock?: KnockStub | unknown;\n /** Permanent alias — always ours, so it works even when `window.knock` is taken. */\n knockai?: KnockStub | unknown;\n }\n}\n\nexport function isStub(value: unknown): value is KnockStub {\n return !!value && Array.isArray((value as KnockStub).q);\n}\n\n/** True for our stub or our facade — anything else on `window.knock` belongs to the host page. */\nexport function isKnockGlobal(value: unknown): boolean {\n return !value || isStub(value) || (value as { __knockai?: true }).__knockai === true;\n}\n","/**\n * Browser global build (`dist/knockai.iife.js`). Loaded by the CDN stub in `snippet.ts`: replays the\n * stub's queue through the real facade, then exposes the facade as `window.knock` (unless the page\n * owns that name) and always as `window.knockai`.\n */\nimport { knock } from './index.js';\nimport { isKnockGlobal, isStub, type StubCall } from './globals.js';\n\nfunction call([path, args, bind]: StubCall): void {\n if (typeof path === 'function') return path();\n const [head, tail] = path.split('.') as [string, string?];\n const target = tail ? Reflect.get(knock, head) : knock;\n const fn = Reflect.get(target as object, tail ?? head);\n if (typeof fn !== 'function') return;\n const result: unknown = fn.apply(target, args);\n if (bind) bind(result);\n}\n\nfunction replay(calls: StubCall[]): void {\n for (const queued of calls) {\n try {\n call(queued);\n } catch {\n // One bad call (e.g. init() with no options) must not drop the calls queued after it.\n }\n }\n}\n\n// Loaded twice: keep the SDK that's already live (and its queue, subscriptions and ready state).\nif (typeof window !== 'undefined' && !(window.knockai as { __knockai?: true } | undefined)?.__knockai) {\n const stub = [window.knockai, window.knock].find(isStub);\n const ownsKnock = isKnockGlobal(window.knock);\n window.knockai = knock;\n if (ownsKnock) window.knock = knock;\n if (stub) replay(stub.q);\n}\n\nexport { knock as default };\n"]}
package/dist/react.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";"use client";var m=Object.defineProperty;var h=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var R=Object.prototype.hasOwnProperty;var I=(t,o)=>{for(var n in o)m(t,n,{get:o[n],enumerable:!0})},g=(t,o,n,e)=>{if(o&&typeof o=="object"||typeof o=="function")for(let r of N(o))!R.call(t,r)&&r!==n&&m(t,r,{get:()=>o[r],enumerable:!(e=h(o,r))||e.enumerable});return t};var S=t=>g(m({},"__esModule",{value:!0}),t);var b={};I(b,{KnockButton:()=>H,KnockProvider:()=>v,useKnock:()=>c,useKnockEvent:()=>B,useKnockIdentify:()=>P});module.exports=S(b);var k=require("react"),d=require("@knock-ai/sdk");var l=require("react"),f=(0,l.createContext)(void 0);var y=require("react/jsx-runtime");function v({user:t,children:o,...n}){let e=(0,k.useRef)(!1);(0,k.useEffect)(()=>{e.current||(e.current=!0,d.knock.init(n))},[]);let r=(0,k.useRef)(void 0);return(0,k.useEffect)(()=>{let i=t?JSON.stringify(t):null;i!==r.current&&(r.current=i,t&&d.knock.identify(t.traits))},[t]),(0,y.jsx)(f.Provider,{value:d.knock,children:o})}var x=require("react"),E=require("@knock-ai/sdk");function c(){var t;return(t=(0,x.useContext)(f))!=null?t:E.knock}var u=require("react");function P(t){let o=c(),n=JSON.stringify(t),e=(0,u.useRef)(void 0);(0,u.useEffect)(()=>{e.current!==n&&(e.current=n,o.identify(t))},[n,o,t])}var p=require("react");function B(t,o){let n=c(),e=(0,p.useRef)(o);e.current=o,(0,p.useEffect)(()=>n.on(t,r=>e.current(r)),[n,t])}var M=require("react/jsx-runtime");function H({magicLinkId:t,email:o,children:n,onClick:e,onPointerEnter:r,onFocus:i,...T}){let K=c(),a=()=>{t&&K.scheduling.load({magicLinkId:t,email:o})};return(0,M.jsx)("button",{type:"button",...T,onClick:s=>{e==null||e(s),K.modal.open({magicLinkId:t,email:o})},onPointerEnter:s=>{r==null||r(s),a()},onFocus:s=>{i==null||i(s),a()},children:n})}0&&(module.exports={KnockButton,KnockProvider,useKnock,useKnockEvent,useKnockIdentify});
2
+ //# sourceMappingURL=react.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/frameworks/react/index.ts","../src/frameworks/react/KnockProvider.tsx","../src/frameworks/react/context.ts","../src/frameworks/react/useKnock.ts","../src/frameworks/react/useKnockIdentify.ts","../src/frameworks/react/useKnockEvent.ts","../src/frameworks/react/KnockButton.tsx"],"sourcesContent":["'use client';\n\nexport { KnockProvider } from './KnockProvider.js';\nexport type { KnockProviderProps, KnockProviderUser } from './KnockProvider.js';\nexport { useKnock } from './useKnock.js';\nexport { useKnockIdentify } from './useKnockIdentify.js';\nexport { useKnockEvent } from './useKnockEvent.js';\nexport { KnockButton } from './KnockButton.js';\nexport type { KnockButtonProps } from './KnockButton.js';\n","import { useEffect, useRef, type ReactNode } from 'react';\nimport type { KnockIdentifyTraits, KnockInitOptions } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\nimport { KnockContext } from './context.js';\n\nexport interface KnockProviderUser {\n traits: KnockIdentifyTraits;\n}\n\nexport interface KnockProviderProps extends KnockInitOptions {\n user?: KnockProviderUser | null;\n children?: ReactNode;\n}\n\nexport function KnockProvider({ user, children, ...initOptions }: KnockProviderProps) {\n const initialized = useRef(false);\n\n useEffect(() => {\n if (initialized.current) return;\n initialized.current = true;\n // init runs once; later prop changes are intentionally ignored (matches `knock.init`'s contract).\n knock.init(initOptions);\n }, []);\n\n const prevUserKey = useRef<string | null | undefined>(undefined);\n\n useEffect(() => {\n const key = user ? JSON.stringify(user) : null;\n if (key === prevUserKey.current) return;\n prevUserKey.current = key;\n if (user) knock.identify(user.traits);\n }, [user]);\n\n return <KnockContext.Provider value={knock}>{children}</KnockContext.Provider>;\n}\n","import { createContext } from 'react';\nimport type { KnockSDK } from '@knock-ai/sdk';\n\n/** No default — useKnock() falls back to the live `knock` singleton outside a provider. */\nexport const KnockContext = createContext<KnockSDK | undefined>(undefined);\n","import { useContext } from 'react';\nimport type { KnockSDK } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\nimport { KnockContext } from './context.js';\n\nexport function useKnock(): KnockSDK {\n return useContext(KnockContext) ?? knock;\n}\n","import { useEffect, useRef } from 'react';\nimport type { KnockIdentifyTraits } from '@knock-ai/sdk';\nimport { useKnock } from './useKnock.js';\n\nexport function useKnockIdentify(traits: KnockIdentifyTraits): void {\n const knock = useKnock();\n const key = JSON.stringify(traits);\n const lastKey = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n if (lastKey.current === key) return;\n lastKey.current = key;\n knock.identify(traits);\n }, [key, knock, traits]);\n}\n","import { useEffect, useRef } from 'react';\nimport type { KnockEventMap, KnockEventName } from '@knock-ai/sdk';\nimport { useKnock } from './useKnock.js';\n\nexport function useKnockEvent<E extends KnockEventName>(\n event: E,\n handler: (payload: KnockEventMap[E]) => void,\n): void {\n const knock = useKnock();\n const handlerRef = useRef(handler);\n handlerRef.current = handler;\n\n // Subscribe once per (knock, event); always dispatch to the latest handler.\n useEffect(() => knock.on(event, (payload) => handlerRef.current(payload)), [knock, event]);\n}\n","import type { ButtonHTMLAttributes, FocusEventHandler, MouseEventHandler, PointerEventHandler, ReactNode } from 'react';\nimport { useKnock } from './useKnock.js';\n\nexport interface KnockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** Omit to open your workspace's default Knock modal. */\n magicLinkId?: string;\n email?: string;\n children?: ReactNode;\n}\n\n/** Loads the scheduling modal on hover or focus, so a click opens it with times already there. */\nexport function KnockButton({ magicLinkId, email, children, onClick, onPointerEnter, onFocus, ...rest }: KnockButtonProps) {\n const knock = useKnock();\n\n const prewarm = () => {\n if (magicLinkId) knock.scheduling.load({ magicLinkId, email });\n };\n const handlePointerEnter: PointerEventHandler<HTMLButtonElement> = (event) => {\n onPointerEnter?.(event);\n prewarm();\n };\n const handleFocus: FocusEventHandler<HTMLButtonElement> = (event) => {\n onFocus?.(event);\n prewarm();\n };\n const handleClick: MouseEventHandler<HTMLButtonElement> = (event) => {\n onClick?.(event);\n knock.modal.open({ magicLinkId, email });\n };\n\n return (\n <button type=\"button\" {...rest} onClick={handleClick} onPointerEnter={handlePointerEnter} onFocus={handleFocus}>\n {children}\n </button>\n );\n}\n"],"mappings":"sbAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,kBAAAC,EAAA,aAAAC,EAAA,kBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAP,GCAA,IAAAQ,EAAkD,iBAElDC,EAAsB,yBCFtB,IAAAC,EAA8B,iBAIjBC,KAAe,iBAAoC,MAAS,ED6BhE,IAAAC,EAAA,6BAnBF,SAASC,EAAc,CAAE,KAAAC,EAAM,SAAAC,EAAU,GAAGC,CAAY,EAAuB,CACpF,IAAMC,KAAc,UAAO,EAAK,KAEhC,aAAU,IAAM,CACVA,EAAY,UAChBA,EAAY,QAAU,GAEtB,QAAM,KAAKD,CAAW,EACxB,EAAG,CAAC,CAAC,EAEL,IAAME,KAAc,UAAkC,MAAS,EAE/D,sBAAU,IAAM,CACd,IAAMC,EAAML,EAAO,KAAK,UAAUA,CAAI,EAAI,KACtCK,IAAQD,EAAY,UACxBA,EAAY,QAAUC,EAClBL,GAAM,QAAM,SAASA,EAAK,MAAM,EACtC,EAAG,CAACA,CAAI,CAAC,KAEF,OAACM,EAAa,SAAb,CAAsB,MAAO,QAAQ,SAAAL,EAAS,CACxD,CElCA,IAAAM,EAA2B,iBAE3BC,EAAsB,yBAGf,SAASC,GAAqB,CALrC,IAAAC,EAME,OAAOA,KAAA,cAAWC,CAAY,IAAvB,KAAAD,EAA4B,OACrC,CCPA,IAAAE,EAAkC,iBAI3B,SAASC,EAAiBC,EAAmC,CAClE,IAAMC,EAAQC,EAAS,EACjBC,EAAM,KAAK,UAAUH,CAAM,EAC3BI,KAAU,UAA2B,MAAS,KAEpD,aAAU,IAAM,CACVA,EAAQ,UAAYD,IACxBC,EAAQ,QAAUD,EAClBF,EAAM,SAASD,CAAM,EACvB,EAAG,CAACG,EAAKF,EAAOD,CAAM,CAAC,CACzB,CCdA,IAAAK,EAAkC,iBAI3B,SAASC,EACdC,EACAC,EACM,CACN,IAAMC,EAAQC,EAAS,EACjBC,KAAa,UAAOH,CAAO,EACjCG,EAAW,QAAUH,KAGrB,aAAU,IAAMC,EAAM,GAAGF,EAAQK,GAAYD,EAAW,QAAQC,CAAO,CAAC,EAAG,CAACH,EAAOF,CAAK,CAAC,CAC3F,CCiBI,IAAAM,EAAA,6BApBG,SAASC,EAAY,CAAE,YAAAC,EAAa,MAAAC,EAAO,SAAAC,EAAU,QAAAC,EAAS,eAAAC,EAAgB,QAAAC,EAAS,GAAGC,CAAK,EAAqB,CACzH,IAAMC,EAAQC,EAAS,EAEjBC,EAAU,IAAM,CAChBT,GAAaO,EAAM,WAAW,KAAK,CAAE,YAAAP,EAAa,MAAAC,CAAM,CAAC,CAC/D,EAcA,SACE,OAAC,UAAO,KAAK,SAAU,GAAGK,EAAM,QANyBI,GAAU,CACnEP,GAAA,MAAAA,EAAUO,GACVH,EAAM,MAAM,KAAK,CAAE,YAAAP,EAAa,MAAAC,CAAM,CAAC,CACzC,EAGwD,eAdYS,GAAU,CAC5EN,GAAA,MAAAA,EAAiBM,GACjBD,EAAQ,CACV,EAW4F,QAVjCC,GAAU,CACnEL,GAAA,MAAAA,EAAUK,GACVD,EAAQ,CACV,EAQK,SAAAP,EACH,CAEJ","names":["react_exports","__export","KnockButton","KnockProvider","useKnock","useKnockEvent","useKnockIdentify","__toCommonJS","import_react","import_sdk","import_react","KnockContext","import_jsx_runtime","KnockProvider","user","children","initOptions","initialized","prevUserKey","key","KnockContext","import_react","import_sdk","useKnock","_a","KnockContext","import_react","useKnockIdentify","traits","knock","useKnock","key","lastKey","import_react","useKnockEvent","event","handler","knock","useKnock","handlerRef","payload","import_jsx_runtime","KnockButton","magicLinkId","email","children","onClick","onPointerEnter","onFocus","rest","knock","useKnock","prewarm","event"]}
package/dist/react.js ADDED
@@ -0,0 +1,2 @@
1
+ "use client";import{useEffect as p,useRef as m}from"react";import{knock as f}from"@knock-ai/sdk";import{createContext as a}from"react";var s=a(void 0);import{jsx as v}from"react/jsx-runtime";function l({user:t,children:n,...e}){let o=m(!1);p(()=>{o.current||(o.current=!0,f.init(e))},[]);let r=m(void 0);return p(()=>{let i=t?JSON.stringify(t):null;i!==r.current&&(r.current=i,t&&f.identify(t.traits))},[t]),v(s.Provider,{value:f,children:n})}import{useContext as y}from"react";import{knock as x}from"@knock-ai/sdk";function c(){var t;return(t=y(s))!=null?t:x}import{useEffect as E,useRef as P}from"react";function B(t){let n=c(),e=JSON.stringify(t),o=P(void 0);E(()=>{o.current!==e&&(o.current=e,n.identify(t))},[e,n,t])}import{useEffect as H,useRef as M}from"react";function T(t,n){let e=c(),o=M(n);o.current=n,H(()=>e.on(t,r=>o.current(r)),[e,t])}import{jsx as N}from"react/jsx-runtime";function h({magicLinkId:t,email:n,children:e,onClick:o,onPointerEnter:r,onFocus:i,...K}){let d=c(),u=()=>{t&&d.scheduling.load({magicLinkId:t,email:n})};return N("button",{type:"button",...K,onClick:k=>{o==null||o(k),d.modal.open({magicLinkId:t,email:n})},onPointerEnter:k=>{r==null||r(k),u()},onFocus:k=>{i==null||i(k),u()},children:e})}export{h as KnockButton,l as KnockProvider,c as useKnock,T as useKnockEvent,B as useKnockIdentify};
2
+ //# sourceMappingURL=react.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/frameworks/react/KnockProvider.tsx","../src/frameworks/react/context.ts","../src/frameworks/react/useKnock.ts","../src/frameworks/react/useKnockIdentify.ts","../src/frameworks/react/useKnockEvent.ts","../src/frameworks/react/KnockButton.tsx"],"sourcesContent":["import { useEffect, useRef, type ReactNode } from 'react';\nimport type { KnockIdentifyTraits, KnockInitOptions } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\nimport { KnockContext } from './context.js';\n\nexport interface KnockProviderUser {\n traits: KnockIdentifyTraits;\n}\n\nexport interface KnockProviderProps extends KnockInitOptions {\n user?: KnockProviderUser | null;\n children?: ReactNode;\n}\n\nexport function KnockProvider({ user, children, ...initOptions }: KnockProviderProps) {\n const initialized = useRef(false);\n\n useEffect(() => {\n if (initialized.current) return;\n initialized.current = true;\n // init runs once; later prop changes are intentionally ignored (matches `knock.init`'s contract).\n knock.init(initOptions);\n }, []);\n\n const prevUserKey = useRef<string | null | undefined>(undefined);\n\n useEffect(() => {\n const key = user ? JSON.stringify(user) : null;\n if (key === prevUserKey.current) return;\n prevUserKey.current = key;\n if (user) knock.identify(user.traits);\n }, [user]);\n\n return <KnockContext.Provider value={knock}>{children}</KnockContext.Provider>;\n}\n","import { createContext } from 'react';\nimport type { KnockSDK } from '@knock-ai/sdk';\n\n/** No default — useKnock() falls back to the live `knock` singleton outside a provider. */\nexport const KnockContext = createContext<KnockSDK | undefined>(undefined);\n","import { useContext } from 'react';\nimport type { KnockSDK } from '@knock-ai/sdk';\nimport { knock } from '@knock-ai/sdk';\nimport { KnockContext } from './context.js';\n\nexport function useKnock(): KnockSDK {\n return useContext(KnockContext) ?? knock;\n}\n","import { useEffect, useRef } from 'react';\nimport type { KnockIdentifyTraits } from '@knock-ai/sdk';\nimport { useKnock } from './useKnock.js';\n\nexport function useKnockIdentify(traits: KnockIdentifyTraits): void {\n const knock = useKnock();\n const key = JSON.stringify(traits);\n const lastKey = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n if (lastKey.current === key) return;\n lastKey.current = key;\n knock.identify(traits);\n }, [key, knock, traits]);\n}\n","import { useEffect, useRef } from 'react';\nimport type { KnockEventMap, KnockEventName } from '@knock-ai/sdk';\nimport { useKnock } from './useKnock.js';\n\nexport function useKnockEvent<E extends KnockEventName>(\n event: E,\n handler: (payload: KnockEventMap[E]) => void,\n): void {\n const knock = useKnock();\n const handlerRef = useRef(handler);\n handlerRef.current = handler;\n\n // Subscribe once per (knock, event); always dispatch to the latest handler.\n useEffect(() => knock.on(event, (payload) => handlerRef.current(payload)), [knock, event]);\n}\n","import type { ButtonHTMLAttributes, FocusEventHandler, MouseEventHandler, PointerEventHandler, ReactNode } from 'react';\nimport { useKnock } from './useKnock.js';\n\nexport interface KnockButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {\n /** Omit to open your workspace's default Knock modal. */\n magicLinkId?: string;\n email?: string;\n children?: ReactNode;\n}\n\n/** Loads the scheduling modal on hover or focus, so a click opens it with times already there. */\nexport function KnockButton({ magicLinkId, email, children, onClick, onPointerEnter, onFocus, ...rest }: KnockButtonProps) {\n const knock = useKnock();\n\n const prewarm = () => {\n if (magicLinkId) knock.scheduling.load({ magicLinkId, email });\n };\n const handlePointerEnter: PointerEventHandler<HTMLButtonElement> = (event) => {\n onPointerEnter?.(event);\n prewarm();\n };\n const handleFocus: FocusEventHandler<HTMLButtonElement> = (event) => {\n onFocus?.(event);\n prewarm();\n };\n const handleClick: MouseEventHandler<HTMLButtonElement> = (event) => {\n onClick?.(event);\n knock.modal.open({ magicLinkId, email });\n };\n\n return (\n <button type=\"button\" {...rest} onClick={handleClick} onPointerEnter={handlePointerEnter} onFocus={handleFocus}>\n {children}\n </button>\n );\n}\n"],"mappings":"aAAA,OAAS,aAAAA,EAAW,UAAAC,MAA8B,QAElD,OAAS,SAAAC,MAAa,gBCFtB,OAAS,iBAAAC,MAAqB,QAIvB,IAAMC,EAAeD,EAAoC,MAAS,ED6BhE,cAAAE,MAAA,oBAnBF,SAASC,EAAc,CAAE,KAAAC,EAAM,SAAAC,EAAU,GAAGC,CAAY,EAAuB,CACpF,IAAMC,EAAcC,EAAO,EAAK,EAEhCC,EAAU,IAAM,CACVF,EAAY,UAChBA,EAAY,QAAU,GAEtBG,EAAM,KAAKJ,CAAW,EACxB,EAAG,CAAC,CAAC,EAEL,IAAMK,EAAcH,EAAkC,MAAS,EAE/D,OAAAC,EAAU,IAAM,CACd,IAAMG,EAAMR,EAAO,KAAK,UAAUA,CAAI,EAAI,KACtCQ,IAAQD,EAAY,UACxBA,EAAY,QAAUC,EAClBR,GAAMM,EAAM,SAASN,EAAK,MAAM,EACtC,EAAG,CAACA,CAAI,CAA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AA,MAAAA,EAAiBM,GACjBD,EAAQ,CACV,EAW4F,QAVjCC,GAAU,CACnEL,GAAA,MAAAA,EAAUK,GACVD,EAAQ,CACV,EAQK,SAAAP,EACH,CAEJ","names":["useEffect","useRef","knock","createContext","KnockContext","jsx","KnockProvider","user","children","initOptions","initialized","useRef","useEffect","knock","prevUserKey","key","KnockContext","useContext","knock","useKnock","_a","useContext","KnockContext","knock","useEffect","useRef","useKnockIdentify","traits","knock","useKnock","key","lastKey","useRef","useEffect","useEffect","useRef","useKnockEvent","event","handler","knock","useKnock","handlerRef","useRef","useEffect","payload","jsx","KnockButton","magicLinkId","email","children","onClick","onPointerEnter","onFocus","rest","knock","useKnock","prewarm","event"]}
@@ -0,0 +1,3 @@
1
+ (function(){'use strict';function w(i){return !!i&&Array.isArray(i.q)}function u(i){return !i||w(i)||i.__knockai===true}var f="https://cdn.jsdelivr.net/npm/@knock-ai/sdk@0.1/dist/knockai.iife.js",S=["init","identify","track","modal.open","modal.close","widget.show","widget.hide","widget.open","widget.close"];(function(){var d,k,l;if(typeof window=="undefined"||window.knockai)return;let r=u(window.knock),s=[],t={q:s,ready:false};for(let c of S){let[n,e]=c.split("."),o=(...p)=>{s.push([c,p]);};e?((d=t[n])!=null?d:t[n]={})[e]=o:t[n]=o;}t.on=(...c)=>{let n,e=["on",c,o=>n=o];return s.push(e),()=>n?n():void(e[0]="")},t.scheduling={load(...c){let n;s.push(["scheduling.load",c,o=>n=o]);let e=o=>()=>n?n[o]():s.push([()=>n[o](),[]]);return {open:e("open"),close:e("close"),get status(){return n?n.status:"loading"}}}},window.knockai=t,r?window.knock=t:console.warn("[knockai] window.knock is taken by this page \u2014 use window.knockai instead");let a=document.createElement("script");a.async=true,a.src=(l=(k=document.currentScript)==null?void 0:k.dataset.knockaiSrc)!=null?l:f,document.head.appendChild(a);})();
2
+ })();//# sourceMappingURL=snippet.js.map
3
+ //# sourceMappingURL=snippet.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/globals.ts","../src/core/snippet.ts"],"names":["isStub","value","isKnockGlobal","FACADE_URL","PATHS","_a","_b","_c","ownsKnock","q","stub","path","head","tail","fn","args","off","call","real","handle","op","method","script"],"mappings":"yBAsBO,SAASA,CAAAA,CAAOC,CAAAA,CAAoC,CACzD,OAAO,CAAC,CAACA,CAAAA,EAAS,KAAA,CAAM,OAAA,CAASA,CAAAA,CAAoB,CAAC,CACxD,CAGO,SAASC,CAAAA,CAAcD,CAAAA,CAAyB,CACrD,OAAO,CAACA,CAAAA,EAASD,CAAAA,CAAOC,CAAK,CAAA,EAAMA,CAAAA,CAA+B,SAAA,GAAc,IAClF,CCnBA,IAAME,EAAa,qEAAA,CACbC,CAAAA,CAAQ,CACZ,MAAA,CACA,UAAA,CACA,OAAA,CACA,YAAA,CACA,aAAA,CACA,aAAA,CACA,aAAA,CACA,aAAA,CACA,cACF,CAAA,CAAA,CAEC,UAA6B,CAvB9B,IAAAC,CAAAA,CAAAC,CAAAA,CAAAC,CAAAA,CAwBE,GAAI,OAAO,MAAA,EAAW,WAAA,EAAe,MAAA,CAAO,OAAA,CAAS,OACrD,IAAMC,CAAAA,CAAYN,CAAAA,CAAc,MAAA,CAAO,KAAK,CAAA,CAEtCO,CAAAA,CAAgB,EAAC,CACjBC,CAAAA,CAAkB,CAAE,CAAA,CAAAD,CAAAA,CAAG,KAAA,CAAO,KAAM,CAAA,CAE1C,IAAA,IAAWE,CAAAA,IAAQP,CAAAA,CAAO,CACxB,GAAM,CAACQ,CAAAA,CAAMC,CAAI,CAAA,CAAIF,CAAAA,CAAK,KAAA,CAAM,GAAG,CAAA,CAC7BG,CAAAA,CAAK,CAAA,GAAIC,CAAAA,GAAiB,CAAQN,CAAAA,CAAE,IAAA,CAAK,CAACE,CAAAA,CAAMI,CAAI,CAAC,EAAA,CAAA,CACvDF,CAAAA,CAAAA,CAAAA,CAAQR,CAAAA,CAAAK,CAAAA,CAAAE,CAAAA,CAAAA,GAAA,IAAA,CAAAP,CAAAA,C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,QAAA,CAAS,aAAA,CAAc,QAAQ,CAAA,CAC9CA,CAAAA,CAAO,KAAA,CAAQ,IAAA,CACfA,CAAAA,CAAO,GAAA,CAAA,CAAOf,CAAAA,CAAAA,CAAAD,CAAAA,CAAA,QAAA,CAAS,aAAA,GAAT,IAAA,CAAA,MAAA,CAAAA,CAAAA,CAAqD,OAAA,CAAQ,UAAA,GAA7D,IAAA,CAAAC,CAAAA,CAA8EJ,CAAAA,CAC5F,QAAA,CAAS,IAAA,CAAK,WAAA,CAAYmB,CAAM,EAClC,CAAA,GAAG","file":"snippet.js","sourcesContent":["/** Shared by the CDN stub and the IIFE facade. No side effects — importing it must never install anything. */\n\n/**\n * Replayed by the IIFE in order: `path` is called on the facade with `args` and `bind` gets its return value;\n * a function `path` (a handle op queued before load) is just called.\n */\nexport type StubCall = [path: string | (() => void), args: unknown[], bind?: (result: unknown) => void];\n\nexport interface KnockStub {\n q: StubCall[];\n [key: string]: unknown;\n}\n\ndeclare global {\n interface Window {\n /** The public global: `knock.identify(...)`. Left alone if the page already owns `window.knock`. */\n knock?: KnockStub | unknown;\n /** Permanent alias — always ours, so it works even when `window.knock` is taken. */\n knockai?: KnockStub | unknown;\n }\n}\n\nexport function isStub(value: unknown): value is KnockStub {\n return !!value && Array.isArray((value as KnockStub).q);\n}\n\n/** True for our stub or our facade — anything else on `window.knock` belongs to the host page. */\nexport function isKnockGlobal(value: unknown): boolean {\n return !value || isStub(value) || (value as { __knockai?: true }).__knockai === true;\n}\n","/**\n * The copy-paste CDN stub. It defines `window.knock` (+ `window.knockai`) as a queue-only stand-in and loads the real\n * facade (`dist/knockai.iife.js`, the same tested core the npm package ships) which then replaces\n * the stub and replays the queue in order. Nothing here talks to the runtime directly.\n *\n * Built standalone by tsup; README/quickstart inline the compiled output verbatim.\n */\nimport type { KnockSchedulingHandle } from './types.js';\nimport { isKnockGlobal, type KnockStub, type StubCall } from './globals.js';\n\nconst FACADE_URL = 'https://cdn.jsdelivr.net/npm/@knock-ai/sdk@0.1/dist/knockai.iife.js';\nconst PATHS = [\n 'init',\n 'identify',\n 'track',\n 'modal.open',\n 'modal.close',\n 'widget.show',\n 'widget.hide',\n 'widget.open',\n 'widget.close',\n];\n\n(function installStub(): void {\n if (typeof window === 'undefined' || window.knockai) return;\n const ownsKnock = isKnockGlobal(window.knock);\n\n const q: StubCall[] = [];\n const stub: KnockStub = { q, ready: false };\n\n for (const path of PATHS) {\n const [head, tail] = path.split('.') as [string, string?];\n const fn = (...args: unknown[]) => void q.push([path, args]);\n if (tail) ((stub[head] ??= {}) as Record<string, unknown>)[tail] = fn;\n else stub[head] = fn;\n }\n\n stub['on'] = (...args: unknown[]): (() => void) => {\n let off: (() => void) | undefined;\n const call: StubCall = ['on', args, (real) => (off = real as () => void)];\n q.push(call);\n // Unsubscribed before the facade loaded: the replay skips a path that isn't a facade method.\n return () => (off ? off() : void (call[0] = ''));\n };\n\n stub['scheduling'] = {\n load(...args: unknown[]): KnockSchedulingHandle {\n let real: KnockSchedulingHandle | undefined;\n q.push(['scheduling.load', args, (handle) => (real = handle as KnockSchedulingHandle)]);\n const op = (method: 'open' | 'close') => () => (real ? real[method]() : q.push([() => real![method](), []]));\n return {\n open: op('open'),\n close: op('close'),\n get status() {\n return real ? real.status : 'loading';\n },\n };\n },\n };\n\n window.knockai = stub;\n if (ownsKnock) window.knock = stub;\n else console.warn('[knockai] window.knock is taken by this page — use window.knockai instead');\n\n const script = document.createElement('script');\n script.async = true;\n script.src = (document.currentScript as HTMLScriptElement | null)?.dataset['knockaiSrc'] ?? FACADE_URL;\n document.head.appendChild(script);\n})();\n"]}
@@ -0,0 +1,2 @@
1
+ 'use strict';var sdk=require('@knock-ai/sdk');function l(){let d=[],i=new Map;function n(e){d.push(e);}function c(){let e="slots_found";return {open(){n({method:"scheduling.handle.open",args:[]}),e="slots_found";},close(){n({method:"scheduling.handle.close",args:[]}),e="closed";},get status(){return e}}}return {ready:true,version:"0.0.0-mock",surface:void 0,calls:d,init(e){n({method:"init",args:[e]});},identify(e){n({method:"identify",args:[e]});},track(e,o){n({method:"track",args:[e,o]});},modal:{open(e={}){n({method:"modal.open",args:[e]});},close(){n({method:"modal.close",args:[]});}},scheduling:{load(e){return n({method:"scheduling.load",args:[e]}),c()}},widget:{show(){n({method:"widget.show",args:[]});},hide(){n({method:"widget.hide",args:[]});},open(){n({method:"widget.open",args:[]});},close(){n({method:"widget.close",args:[]});}},clearCalls(){d.length=0;},on(e,o){n({method:"on",args:[e]});let t=i.get(e);return t||(t=new Set,i.set(e,t)),t.add(o),()=>{var a;(a=i.get(e))==null||a.delete(o);}},emit(e,o){let t=i.get(e);if(t)for(let a of t)a(o);},lastIdentify(){for(let e=d.length-1;e>=0;e-=1){let o=d[e];if((o==null?void 0:o.method)==="identify")return {traits:o.args[0]}}},eventsNamed(e){let o=[];for(let t of d)t.method==="track"&&t.args[0]===e&&o.push(t.args[1]);return o}}}function g(d){sdk.__setKnockForTesting(d);}function h(){sdk.__setKnockForTesting(void 0);}exports.createKnockMock=l;exports.installKnockMock=g;exports.uninstallKnockMock=h;//# sourceMappingURL=testing.cjs.map
2
+ //# sourceMappingURL=testing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing/index.ts"],"names":["createKnockMock","calls","listeners","record","call","createSchedulingHandle","status","options","traits","eventName","properties","event","handler","set","_a","payload","i","name","result","installKnockMock","mock","__setKnockForTesting","uninstallKnockMock"],"mappings":"8CAmDO,SAASA,CAAAA,EAA6B,CAC3C,IAAMC,CAAAA,CAAyB,GACzBC,CAAAA,CAAY,IAAI,IAEtB,SAASC,CAAAA,CAAOC,EAA2B,CACzCH,CAAAA,CAAM,KAAKG,CAAI,EACjB,CAEA,SAASC,CAAAA,EAAgD,CACvD,IAAIC,CAAAA,CAAgC,cACpC,OAAO,CACL,MAAa,CACXH,CAAAA,CAAO,CAAE,MAAA,CAAQ,wBAAA,CAA0B,KAAM,EAAG,CAAC,CAAA,CACrDG,CAAAA,CAAS,cACX,CAAA,C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,CAEF,CAAA,CAEA,YAAYa,CAAAA,CAAM,CAChB,IAAMC,CAAAA,CAA6D,GACnE,IAAA,IAAWd,CAAAA,IAAQH,EACbG,CAAAA,CAAK,MAAA,GAAW,SAAWA,CAAAA,CAAK,IAAA,CAAK,CAAC,CAAA,GAAMa,CAAAA,EAC9CC,EAAO,IAAA,CAAKd,CAAAA,CAAK,KAAK,CAAC,CAAC,EAG5B,OAAOc,CACT,CACF,CACF,CAGO,SAASC,CAAAA,CAAiBC,CAAAA,CAAuB,CACtDC,wBAAAA,CAAqBD,CAAI,EAC3B,CAGO,SAASE,GAA2B,CACzCD,wBAAAA,CAAqB,MAAS,EAChC","file":"testing.cjs","sourcesContent":["/**\n * In-memory test double for the `@knock-ai/sdk` facade. Zero DOM access — every method\n * just records what was called so tests can assert on it.\n *\n * `installKnockMock`/`uninstallKnockMock` expect `../core` to export\n * `__setKnockForTesting(sdk: KnockSDK | undefined): void`, a test-only hook the\n * framework bindings resolve their singleton through.\n */\nimport { __setKnockForTesting } from '@knock-ai/sdk';\nimport type {\n KnockEventMap,\n KnockEventName,\n KnockFieldValue,\n KnockIdentifyTraits,\n KnockInitOptions,\n KnockModalOpenOptions,\n KnockSDK,\n KnockSchedulingHandle,\n KnockSchedulingLoadOptions,\n KnockSchedulingStatus,\n} from '../core/types.js';\n\nexport type KnockMockCall =\n | { method: 'init'; args: [KnockInitOptions] }\n | { method: 'identify'; args: [KnockIdentifyTraits] }\n | { method: 'track'; args: [string, Record<string, KnockFieldValue> | undefined] }\n | { method: 'modal.open'; args: [KnockModalOpenOptions] }\n | { method: 'modal.close'; args: [] }\n | { method: 'scheduling.load'; args: [KnockSchedulingLoadOptions] }\n | { method: 'scheduling.handle.open'; args: [] }\n | { method: 'scheduling.handle.close'; args: [] }\n | { method: 'widget.show'; args: [] }\n | { method: 'widget.hide'; args: [] }\n | { method: 'widget.open'; args: [] }\n | { method: 'widget.close'; args: [] }\n | { method: 'on'; args: [KnockEventName] };\n\nexport interface KnockMock extends KnockSDK {\n /** Every call made against this mock, oldest first. */\n readonly calls: readonly KnockMockCall[];\n /** Traits from the most recent `identify()` call, if any. */\n lastIdentify(): { traits: KnockIdentifyTraits } | undefined;\n /** Properties from every `track(name, …)` call, in call order. */\n eventsNamed(name: string): Array<Record<string, KnockFieldValue> | undefined>;\n /** Fire a handler registered via `on()`, as the real runtime would. */\n emit<E extends KnockEventName>(event: E, payload: KnockEventMap[E]): void;\n /** Forget recorded calls; `on()` subscriptions stay. */\n clearCalls(): void;\n}\n\n/** A full, in-memory `KnockSDK` that records every call for assertions. */\nexport function createKnockMock(): KnockMock {\n const calls: KnockMockCall[] = [];\n const listeners = new Map<KnockEventName, Set<(payload: never) => void>>();\n\n function record(call: KnockMockCall): void {\n calls.push(call);\n }\n\n function createSchedulingHandle(): KnockSchedulingHandle {\n let status: KnockSchedulingStatus = 'slots_found';\n return {\n open(): void {\n record({ method: 'scheduling.handle.open', args: [] });\n status = 'slots_found';\n },\n close(): void {\n record({ method: 'scheduling.handle.close', args: [] });\n status = 'closed';\n },\n get status(): KnockSchedulingStatus {\n return status;\n },\n };\n }\n\n return {\n ready: true,\n version: '0.0.0-mock',\n surface: undefined,\n calls,\n\n init(options): void {\n record({ method: 'init', args: [options] });\n },\n\n identify(traits): void {\n record({ method: 'identify', args: [traits] });\n },\n\n track(eventName, properties): void {\n record({ method: 'track', args: [eventName, properties] });\n },\n\n modal: {\n open(options = {}): void {\n record({ method: 'modal.open', args: [options] });\n },\n close(): void {\n record({ method: 'modal.close', args: [] });\n },\n },\n\n scheduling: {\n load(options): KnockSchedulingHandle {\n record({ method: 'scheduling.load', args: [options] });\n return createSchedulingHandle();\n },\n },\n\n widget: {\n show(): void {\n record({ method: 'widget.show', args: [] });\n },\n hide(): void {\n record({ method: 'widget.hide', args: [] });\n },\n open(): void {\n record({ method: 'widget.open', args: [] });\n },\n close(): void {\n record({ method: 'widget.close', args: [] });\n },\n },\n\n clearCalls(): void {\n calls.length = 0;\n },\n\n on<E extends KnockEventName>(event: E, handler: (payload: KnockEventMap[E]) => void): () => void {\n record({ method: 'on', args: [event] });\n let set = listeners.get(event);\n if (!set) {\n set = new Set();\n listeners.set(event, set);\n }\n set.add(handler);\n return () => {\n listeners.get(event)?.delete(handler);\n };\n },\n\n emit<E extends KnockEventName>(event: E, payload: KnockEventMap[E]): void {\n const set = listeners.get(event);\n if (!set) return;\n // handlers are stored with their per-event type erased to `never`; this is the one\n // place that needs to undo it to actually invoke them.\n for (const handler of set) handler(payload as never);\n },\n\n lastIdentify() {\n for (let i = calls.length - 1; i >= 0; i -= 1) {\n const call = calls[i];\n if (call?.method === 'identify') {\n return { traits: call.args[0] };\n }\n }\n return undefined;\n },\n\n eventsNamed(name) {\n const result: Array<Record<string, KnockFieldValue> | undefined> = [];\n for (const call of calls) {\n if (call.method === 'track' && call.args[0] === name) {\n result.push(call.args[1]);\n }\n }\n return result;\n },\n };\n}\n\n/** Swap the singleton the framework bindings resolve `knock` through onto `mock`. */\nexport function installKnockMock(mock: KnockMock): void {\n __setKnockForTesting(mock);\n}\n\n/** Restore the framework bindings to the real (queueing) facade singleton. */\nexport function uninstallKnockMock(): void {\n __setKnockForTesting(undefined);\n}\n"]}