@zerogpu/browser-extension-sdk 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,8 +4,8 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZeroGpuBrowserSdk = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- const SDK_VERSION = typeof "0.2.3+38ce04b" === 'string' && "0.2.3+38ce04b".length > 0
8
- ? "0.2.3+38ce04b"
7
+ const SDK_VERSION = typeof "0.3.0+b41a26f" === 'string' && "0.3.0+b41a26f".length > 0
8
+ ? "0.3.0+b41a26f"
9
9
  : '0.0.0-dev';
10
10
 
11
11
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -173,7 +173,7 @@
173
173
  return cap(value, ID_MAX);
174
174
  return `[string:${value.length}]`;
175
175
  };
176
- const sanitizeValue = (key, value) => {
176
+ const sanitizeValue$1 = (key, value) => {
177
177
  if (CREDENTIAL_KEY_PATTERN.test(key))
178
178
  return '[redacted]';
179
179
  if (value === null || value === undefined)
@@ -198,7 +198,7 @@
198
198
  return { error: summarizeError(fields) };
199
199
  }
200
200
  if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
201
- return { detail: sanitizeValue('detail', fields) };
201
+ return { detail: sanitizeValue$1('detail', fields) };
202
202
  }
203
203
  const sanitized = {};
204
204
  for (const [key, value] of Object.entries(fields)) {
@@ -207,14 +207,14 @@
207
207
  sanitized[key] = '[redacted]';
208
208
  }
209
209
  else if (value.every((item) => item === null || typeof item !== 'object')) {
210
- sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
210
+ sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue$1(key, item));
211
211
  }
212
212
  else {
213
213
  sanitized[key] = describeOpaque(value);
214
214
  }
215
215
  continue;
216
216
  }
217
- sanitized[key] = sanitizeValue(key, value);
217
+ sanitized[key] = sanitizeValue$1(key, value);
218
218
  }
219
219
  return sanitized;
220
220
  };
@@ -2126,6 +2126,140 @@
2126
2126
  return fireBeacon(url, timeoutMs);
2127
2127
  };
2128
2128
 
2129
+ /**
2130
+ * Operator macros: three opaque slots an app attaches to every request its
2131
+ * devices serve. ZeroGPU stores and counts them, never interprets them, and
2132
+ * reports them back only to the operator that owns the SDK key.
2133
+ */
2134
+ const CUST_PARAM_SLOTS = ['cust_param1', 'cust_param2', 'cust_param3'];
2135
+ /** Longer values are truncated, never rejected — the server applies the same cap. */
2136
+ const CUST_PARAM_MAX_LENGTH = 128;
2137
+ /**
2138
+ * A slot takes a bare value (`1231231313`, `plan_a`), never a nested
2139
+ * parameter: the slot name is the key, so `user-id=123` is dropped. The server
2140
+ * enforces the same set (@zerogpu/global-types CUST_PARAM_VALUE_PATTERN).
2141
+ */
2142
+ const CUST_PARAM_VALUE_PATTERN = /^[A-Za-z0-9._-]+$/;
2143
+ const isControlChar = (codePoint) => codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
2144
+ const EMAIL_SHAPED = /[^\s@]+@[^\s@]+\.[^\s@]+/;
2145
+ const isSlot = (key) => CUST_PARAM_SLOTS.includes(key);
2146
+ let truncationWarned = false;
2147
+ const sanitizeValue = (slot, raw) => {
2148
+ if (raw === undefined || raw === null)
2149
+ return undefined;
2150
+ let value;
2151
+ if (typeof raw === 'string') {
2152
+ value = raw;
2153
+ }
2154
+ else if ((typeof raw === 'number' && Number.isFinite(raw)) || typeof raw === 'boolean') {
2155
+ value = String(raw);
2156
+ }
2157
+ else {
2158
+ getLogger().warn('[CustomParams] Dropped a value that is not a string, number or boolean', {
2159
+ name: slot,
2160
+ type: typeof raw
2161
+ });
2162
+ return undefined;
2163
+ }
2164
+ value = Array.from(value)
2165
+ .filter((char) => !isControlChar(char.codePointAt(0) ?? 0))
2166
+ .join('')
2167
+ .trim();
2168
+ if (!value)
2169
+ return undefined;
2170
+ // A slot is reported back verbatim and cannot be deleted per value, so an
2171
+ // email address in one is a data-protection problem, not a formatting one.
2172
+ // Loud regardless of enableConsoleLogs: this is an integration mistake that
2173
+ // otherwise shows up only as a silently empty slot.
2174
+ if (EMAIL_SHAPED.test(value)) {
2175
+ // eslint-disable-next-line no-console
2176
+ console.warn(`[ZeroGPU] customParams.${slot} looks like an email address and was dropped. Slots must not carry personal data.`);
2177
+ return undefined;
2178
+ }
2179
+ // Loud for the same reason: the server would drop it too, and the value is
2180
+ // left out of the message in case it is someone's identifier.
2181
+ if (!CUST_PARAM_VALUE_PATTERN.test(value)) {
2182
+ // eslint-disable-next-line no-console
2183
+ console.warn(`[ZeroGPU] customParams.${slot} was dropped. A slot takes just a value (letters, digits, "." "_" "-"), not a nested parameter such as "user-id=123".`);
2184
+ return undefined;
2185
+ }
2186
+ if (value.length > CUST_PARAM_MAX_LENGTH) {
2187
+ if (!truncationWarned) {
2188
+ truncationWarned = true;
2189
+ getLogger().warn('[CustomParams] Value truncated', {
2190
+ name: slot,
2191
+ length: value.length,
2192
+ maxLength: CUST_PARAM_MAX_LENGTH
2193
+ });
2194
+ }
2195
+ value = value.slice(0, CUST_PARAM_MAX_LENGTH);
2196
+ }
2197
+ return value;
2198
+ };
2199
+ /**
2200
+ * Normalizes host input to the slots the server accepts. Never throws: a bad
2201
+ * value is dropped (with a warning) so a macro mistake can never stop the SDK.
2202
+ * Unset, empty and dropped slots are all simply absent from the result.
2203
+ */
2204
+ const sanitizeCustomParams = (input) => {
2205
+ const resolved = {};
2206
+ if (input === undefined || input === null)
2207
+ return resolved;
2208
+ if (typeof input !== 'object' || Array.isArray(input)) {
2209
+ getLogger().warn('[CustomParams] Ignored: expected an object of cust_param1..3', {
2210
+ type: Array.isArray(input) ? 'array' : typeof input
2211
+ });
2212
+ return resolved;
2213
+ }
2214
+ const source = input;
2215
+ // Host objects can be Proxies or carry getters, and either can throw on read.
2216
+ let keys;
2217
+ try {
2218
+ keys = Object.keys(source);
2219
+ }
2220
+ catch {
2221
+ getLogger().warn('[CustomParams] Ignored: the object could not be read');
2222
+ return resolved;
2223
+ }
2224
+ for (const key of keys) {
2225
+ if (!isSlot(key)) {
2226
+ getLogger().warn('[CustomParams] Ignored an unknown key; only cust_param1..3 are accepted', {
2227
+ name: key
2228
+ });
2229
+ continue;
2230
+ }
2231
+ let raw;
2232
+ try {
2233
+ raw = source[key];
2234
+ }
2235
+ catch {
2236
+ getLogger().warn('[CustomParams] Dropped a value that could not be read', { name: key });
2237
+ continue;
2238
+ }
2239
+ const value = sanitizeValue(key, raw);
2240
+ if (value !== undefined)
2241
+ resolved[key] = value;
2242
+ }
2243
+ return resolved;
2244
+ };
2245
+ let current = {};
2246
+ /** Replaces the whole map: slots omitted from `input` become unset. */
2247
+ const setCustomParamsState = (input) => {
2248
+ current = sanitizeCustomParams(input);
2249
+ };
2250
+ /** Only the set slots — spread flat onto the register body. */
2251
+ const getRegisterCustomParams = () => ({ ...current });
2252
+ /**
2253
+ * Every slot, `''` when unset. The server merges per job over the register-time
2254
+ * values slot by slot, and an explicit `''` is what clears a slot that was set
2255
+ * at register time — omitting it would leave the stale value in place.
2256
+ */
2257
+ const getTaskResultCustomParams = () => ({
2258
+ cust_param1: current.cust_param1 ?? '',
2259
+ cust_param2: current.cust_param2 ?? '',
2260
+ cust_param3: current.cust_param3 ?? ''
2261
+ });
2262
+
2129
2263
  let executing = false;
2130
2264
  const buildInferenceInput = (request) => {
2131
2265
  const input = request.input ?? {};
@@ -2177,6 +2311,12 @@
2177
2311
  const executeSingleRequest = async (request) => {
2178
2312
  const logger = getLogger();
2179
2313
  const start = performance.now();
2314
+ // Snapshot before the first await. The macros are module state a host can
2315
+ // replace at any time via setCustomParams, and everything below — the lazy
2316
+ // adapter load, inference, the pixel turn — yields. Reading them at result
2317
+ // time would attribute an in-flight request to whatever the host switched to
2318
+ // mid-flight, breaking the documented "applies from the next request served".
2319
+ const custParams = getTaskResultCustomParams();
2180
2320
  const { adaptersByModelId } = getState();
2181
2321
  let adapter = adaptersByModelId?.[request.modelId];
2182
2322
  if (!adapter) {
@@ -2269,7 +2409,8 @@
2269
2409
  errorMessage: '',
2270
2410
  metadata: {
2271
2411
  processingTime: Math.round(performance.now() - start),
2272
- ...(await pixelMetadata())
2412
+ ...(await pixelMetadata()),
2413
+ customParams: custParams
2273
2414
  }
2274
2415
  };
2275
2416
  }
@@ -3143,7 +3284,8 @@
3143
3284
  cachedModels: cachedInfo && !cacheInvalid
3144
3285
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3145
3286
  : [],
3146
- device: deviceInfo
3287
+ device: deviceInfo,
3288
+ ...getRegisterCustomParams()
3147
3289
  };
3148
3290
  let registerResponse;
3149
3291
  let assignedModels = [];
@@ -5180,6 +5322,12 @@
5180
5322
  }
5181
5323
  }
5182
5324
  const config = resolveConfig(options?.overrides);
5325
+ if (options?.customParams !== undefined) {
5326
+ // Validation warnings go through the logger, which startLifecycle would
5327
+ // otherwise only configure after the values are already applied.
5328
+ initLogger(config.telemetry);
5329
+ setCustomParamsState(options.customParams);
5330
+ }
5183
5331
  try {
5184
5332
  await startLifecycle({
5185
5333
  config,
@@ -5195,6 +5343,14 @@
5195
5343
  }
5196
5344
  return handle;
5197
5345
  };
5346
+ /**
5347
+ * Replaces the operator macros: slots omitted here become unset, and
5348
+ * `setCustomParams({})` clears them all. Applies from the next request the
5349
+ * device serves — no re-registration. Safe to call before or after init.
5350
+ */
5351
+ const setCustomParams = (params) => {
5352
+ setCustomParamsState(params);
5353
+ };
5198
5354
 
5199
5355
  const readAttr = (script, names) => {
5200
5356
  for (const name of names) {
@@ -5272,6 +5428,17 @@
5272
5428
  readSearchParam(searchParams, ['device-id', 'deviceId']),
5273
5429
  edgeOperatorKey
5274
5430
  };
5431
+ const customParams = {};
5432
+ for (const slot of CUST_PARAM_SLOTS) {
5433
+ const suffix = slot.slice('cust_param'.length);
5434
+ const value = readAttr(script, [`data-cust-param${suffix}`, slot]) ??
5435
+ readSearchParam(searchParams, [`cust-param${suffix}`, slot]);
5436
+ if (value !== undefined)
5437
+ customParams[slot] = value;
5438
+ }
5439
+ if (Object.keys(customParams).length > 0) {
5440
+ options.customParams = customParams;
5441
+ }
5275
5442
  const enableConsoleLogs = readBooleanAttr(script, ['data-enable-console-logs', 'enableConsoleLogs']) ??
5276
5443
  (() => {
5277
5444
  const value = readSearchParam(searchParams, ['enable-console-logs', 'enableConsoleLogs']);
@@ -5323,6 +5490,7 @@
5323
5490
  autoInitFromScriptTag();
5324
5491
 
5325
5492
  exports.initZeroGpuSdk = initZeroGpuSdk;
5493
+ exports.setCustomParams = setCustomParams;
5326
5494
 
5327
5495
  }));
5328
5496
  //# sourceMappingURL=zerogpu-browser-sdk.umd.js.map