@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.
@@ -1,5 +1,5 @@
1
- const SDK_VERSION = typeof "0.2.3+38ce04b" === 'string' && "0.2.3+38ce04b".length > 0
2
- ? "0.2.3+38ce04b"
1
+ const SDK_VERSION = typeof "0.3.0+b41a26f" === 'string' && "0.3.0+b41a26f".length > 0
2
+ ? "0.3.0+b41a26f"
3
3
  : '0.0.0-dev';
4
4
 
5
5
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -167,7 +167,7 @@ const sanitizeString = (key, value) => {
167
167
  return cap(value, ID_MAX);
168
168
  return `[string:${value.length}]`;
169
169
  };
170
- const sanitizeValue = (key, value) => {
170
+ const sanitizeValue$1 = (key, value) => {
171
171
  if (CREDENTIAL_KEY_PATTERN.test(key))
172
172
  return '[redacted]';
173
173
  if (value === null || value === undefined)
@@ -192,7 +192,7 @@ const sanitizeLogFields = (fields) => {
192
192
  return { error: summarizeError(fields) };
193
193
  }
194
194
  if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
195
- return { detail: sanitizeValue('detail', fields) };
195
+ return { detail: sanitizeValue$1('detail', fields) };
196
196
  }
197
197
  const sanitized = {};
198
198
  for (const [key, value] of Object.entries(fields)) {
@@ -201,14 +201,14 @@ const sanitizeLogFields = (fields) => {
201
201
  sanitized[key] = '[redacted]';
202
202
  }
203
203
  else if (value.every((item) => item === null || typeof item !== 'object')) {
204
- sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
204
+ sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue$1(key, item));
205
205
  }
206
206
  else {
207
207
  sanitized[key] = describeOpaque(value);
208
208
  }
209
209
  continue;
210
210
  }
211
- sanitized[key] = sanitizeValue(key, value);
211
+ sanitized[key] = sanitizeValue$1(key, value);
212
212
  }
213
213
  return sanitized;
214
214
  };
@@ -2175,6 +2175,140 @@ const fireTrackingScript = async (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
2175
2175
  return fireBeacon(url, timeoutMs);
2176
2176
  };
2177
2177
 
2178
+ /**
2179
+ * Operator macros: three opaque slots an app attaches to every request its
2180
+ * devices serve. ZeroGPU stores and counts them, never interprets them, and
2181
+ * reports them back only to the operator that owns the SDK key.
2182
+ */
2183
+ const CUST_PARAM_SLOTS = ['cust_param1', 'cust_param2', 'cust_param3'];
2184
+ /** Longer values are truncated, never rejected — the server applies the same cap. */
2185
+ const CUST_PARAM_MAX_LENGTH = 128;
2186
+ /**
2187
+ * A slot takes a bare value (`1231231313`, `plan_a`), never a nested
2188
+ * parameter: the slot name is the key, so `user-id=123` is dropped. The server
2189
+ * enforces the same set (@zerogpu/global-types CUST_PARAM_VALUE_PATTERN).
2190
+ */
2191
+ const CUST_PARAM_VALUE_PATTERN = /^[A-Za-z0-9._-]+$/;
2192
+ const isControlChar = (codePoint) => codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f);
2193
+ const EMAIL_SHAPED = /[^\s@]+@[^\s@]+\.[^\s@]+/;
2194
+ const isSlot = (key) => CUST_PARAM_SLOTS.includes(key);
2195
+ let truncationWarned = false;
2196
+ const sanitizeValue = (slot, raw) => {
2197
+ if (raw === undefined || raw === null)
2198
+ return undefined;
2199
+ let value;
2200
+ if (typeof raw === 'string') {
2201
+ value = raw;
2202
+ }
2203
+ else if ((typeof raw === 'number' && Number.isFinite(raw)) || typeof raw === 'boolean') {
2204
+ value = String(raw);
2205
+ }
2206
+ else {
2207
+ getLogger().warn('[CustomParams] Dropped a value that is not a string, number or boolean', {
2208
+ name: slot,
2209
+ type: typeof raw
2210
+ });
2211
+ return undefined;
2212
+ }
2213
+ value = Array.from(value)
2214
+ .filter((char) => !isControlChar(char.codePointAt(0) ?? 0))
2215
+ .join('')
2216
+ .trim();
2217
+ if (!value)
2218
+ return undefined;
2219
+ // A slot is reported back verbatim and cannot be deleted per value, so an
2220
+ // email address in one is a data-protection problem, not a formatting one.
2221
+ // Loud regardless of enableConsoleLogs: this is an integration mistake that
2222
+ // otherwise shows up only as a silently empty slot.
2223
+ if (EMAIL_SHAPED.test(value)) {
2224
+ // eslint-disable-next-line no-console
2225
+ console.warn(`[ZeroGPU] customParams.${slot} looks like an email address and was dropped. Slots must not carry personal data.`);
2226
+ return undefined;
2227
+ }
2228
+ // Loud for the same reason: the server would drop it too, and the value is
2229
+ // left out of the message in case it is someone's identifier.
2230
+ if (!CUST_PARAM_VALUE_PATTERN.test(value)) {
2231
+ // eslint-disable-next-line no-console
2232
+ console.warn(`[ZeroGPU] customParams.${slot} was dropped. A slot takes just a value (letters, digits, "." "_" "-"), not a nested parameter such as "user-id=123".`);
2233
+ return undefined;
2234
+ }
2235
+ if (value.length > CUST_PARAM_MAX_LENGTH) {
2236
+ if (!truncationWarned) {
2237
+ truncationWarned = true;
2238
+ getLogger().warn('[CustomParams] Value truncated', {
2239
+ name: slot,
2240
+ length: value.length,
2241
+ maxLength: CUST_PARAM_MAX_LENGTH
2242
+ });
2243
+ }
2244
+ value = value.slice(0, CUST_PARAM_MAX_LENGTH);
2245
+ }
2246
+ return value;
2247
+ };
2248
+ /**
2249
+ * Normalizes host input to the slots the server accepts. Never throws: a bad
2250
+ * value is dropped (with a warning) so a macro mistake can never stop the SDK.
2251
+ * Unset, empty and dropped slots are all simply absent from the result.
2252
+ */
2253
+ const sanitizeCustomParams = (input) => {
2254
+ const resolved = {};
2255
+ if (input === undefined || input === null)
2256
+ return resolved;
2257
+ if (typeof input !== 'object' || Array.isArray(input)) {
2258
+ getLogger().warn('[CustomParams] Ignored: expected an object of cust_param1..3', {
2259
+ type: Array.isArray(input) ? 'array' : typeof input
2260
+ });
2261
+ return resolved;
2262
+ }
2263
+ const source = input;
2264
+ // Host objects can be Proxies or carry getters, and either can throw on read.
2265
+ let keys;
2266
+ try {
2267
+ keys = Object.keys(source);
2268
+ }
2269
+ catch {
2270
+ getLogger().warn('[CustomParams] Ignored: the object could not be read');
2271
+ return resolved;
2272
+ }
2273
+ for (const key of keys) {
2274
+ if (!isSlot(key)) {
2275
+ getLogger().warn('[CustomParams] Ignored an unknown key; only cust_param1..3 are accepted', {
2276
+ name: key
2277
+ });
2278
+ continue;
2279
+ }
2280
+ let raw;
2281
+ try {
2282
+ raw = source[key];
2283
+ }
2284
+ catch {
2285
+ getLogger().warn('[CustomParams] Dropped a value that could not be read', { name: key });
2286
+ continue;
2287
+ }
2288
+ const value = sanitizeValue(key, raw);
2289
+ if (value !== undefined)
2290
+ resolved[key] = value;
2291
+ }
2292
+ return resolved;
2293
+ };
2294
+ let current = {};
2295
+ /** Replaces the whole map: slots omitted from `input` become unset. */
2296
+ const setCustomParamsState = (input) => {
2297
+ current = sanitizeCustomParams(input);
2298
+ };
2299
+ /** Only the set slots — spread flat onto the register body. */
2300
+ const getRegisterCustomParams = () => ({ ...current });
2301
+ /**
2302
+ * Every slot, `''` when unset. The server merges per job over the register-time
2303
+ * values slot by slot, and an explicit `''` is what clears a slot that was set
2304
+ * at register time — omitting it would leave the stale value in place.
2305
+ */
2306
+ const getTaskResultCustomParams = () => ({
2307
+ cust_param1: current.cust_param1 ?? '',
2308
+ cust_param2: current.cust_param2 ?? '',
2309
+ cust_param3: current.cust_param3 ?? ''
2310
+ });
2311
+
2178
2312
  let executing = false;
2179
2313
  const buildInferenceInput = (request) => {
2180
2314
  const input = request.input ?? {};
@@ -2226,6 +2360,12 @@ const lazyLoadAdapter = async (modelId) => {
2226
2360
  const executeSingleRequest = async (request) => {
2227
2361
  const logger = getLogger();
2228
2362
  const start = performance.now();
2363
+ // Snapshot before the first await. The macros are module state a host can
2364
+ // replace at any time via setCustomParams, and everything below — the lazy
2365
+ // adapter load, inference, the pixel turn — yields. Reading them at result
2366
+ // time would attribute an in-flight request to whatever the host switched to
2367
+ // mid-flight, breaking the documented "applies from the next request served".
2368
+ const custParams = getTaskResultCustomParams();
2229
2369
  const { adaptersByModelId } = getState();
2230
2370
  let adapter = adaptersByModelId?.[request.modelId];
2231
2371
  if (!adapter) {
@@ -2318,7 +2458,8 @@ const executeSingleRequest = async (request) => {
2318
2458
  errorMessage: '',
2319
2459
  metadata: {
2320
2460
  processingTime: Math.round(performance.now() - start),
2321
- ...(await pixelMetadata())
2461
+ ...(await pixelMetadata()),
2462
+ customParams: custParams
2322
2463
  }
2323
2464
  };
2324
2465
  }
@@ -3192,7 +3333,8 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3192
3333
  cachedModels: cachedInfo && !cacheInvalid
3193
3334
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3194
3335
  : [],
3195
- device: deviceInfo
3336
+ device: deviceInfo,
3337
+ ...getRegisterCustomParams()
3196
3338
  };
3197
3339
  let registerResponse;
3198
3340
  let assignedModels = [];
@@ -5229,6 +5371,12 @@ const initZeroGpuSdk = async (options) => {
5229
5371
  }
5230
5372
  }
5231
5373
  const config = resolveConfig(options?.overrides);
5374
+ if (options?.customParams !== undefined) {
5375
+ // Validation warnings go through the logger, which startLifecycle would
5376
+ // otherwise only configure after the values are already applied.
5377
+ initLogger(config.telemetry);
5378
+ setCustomParamsState(options.customParams);
5379
+ }
5232
5380
  try {
5233
5381
  await startLifecycle({
5234
5382
  config,
@@ -5244,6 +5392,14 @@ const initZeroGpuSdk = async (options) => {
5244
5392
  }
5245
5393
  return handle;
5246
5394
  };
5395
+ /**
5396
+ * Replaces the operator macros: slots omitted here become unset, and
5397
+ * `setCustomParams({})` clears them all. Applies from the next request the
5398
+ * device serves — no re-registration. Safe to call before or after init.
5399
+ */
5400
+ const setCustomParams = (params) => {
5401
+ setCustomParamsState(params);
5402
+ };
5247
5403
 
5248
5404
  /**
5249
5405
  * ZeroGPU "extension kit" — end-user consent store.
@@ -5304,6 +5460,15 @@ const getZeroGpuConsent = async () => {
5304
5460
  return DEFAULT_CONSENT;
5305
5461
  }
5306
5462
  };
5463
+ /**
5464
+ * Serialises writes, for the same reason the bridge serialises applies. Toggling
5465
+ * twice in quick succession is two concurrent calls — each bridge message is
5466
+ * handled independently — and `storage.local` promises no ordering between
5467
+ * them, so the earlier decision could be the one that lands last and persists
5468
+ * while the user is looking at the later one. Queueing also keeps `updatedAt`
5469
+ * in step with what actually got stored.
5470
+ */
5471
+ Promise.resolve();
5307
5472
  /**
5308
5473
  * Subscribe to consent changes from any extension context (the hosted settings
5309
5474
  * page writing through the service worker, the options page, another window).
@@ -5499,6 +5664,7 @@ const initZeroGpuOffscreen = async (options = {}) => {
5499
5664
  edgeOperatorKey: options.edgeOperatorKey,
5500
5665
  appUserId: options.appUserId,
5501
5666
  deviceId: options.deviceId,
5667
+ customParams: options.customParams,
5502
5668
  overrides: buildOverrides(options)
5503
5669
  });
5504
5670
  };
@@ -5509,7 +5675,8 @@ const initZeroGpuOffscreen = async (options = {}) => {
5509
5675
  const ZEROGPU_OFFSCREEN_MESSAGES = {
5510
5676
  forceInit: 'zerogpu:forceInit',
5511
5677
  getStatus: 'zerogpu:getStatus',
5512
- disable: 'zerogpu:disable'
5678
+ disable: 'zerogpu:disable',
5679
+ setCustomParams: 'zerogpu:setCustomParams'
5513
5680
  };
5514
5681
  /**
5515
5682
  * Wire the offscreen document to the standard popup/background debug protocol.
@@ -5566,6 +5733,11 @@ const registerZeroGpuOffscreenMessaging = (options = {}) => {
5566
5733
  }));
5567
5734
  return true;
5568
5735
  }
5736
+ if (message.type === ZEROGPU_OFFSCREEN_MESSAGES.setCustomParams) {
5737
+ setCustomParams(message.customParams ?? {});
5738
+ sendResponse({ ok: true });
5739
+ return;
5740
+ }
5569
5741
  if (message.type === ZEROGPU_OFFSCREEN_MESSAGES.disable) {
5570
5742
  // The offscreen document may be torn down after this — run the full
5571
5743
  // ordered shutdown (gate tasks, close the socket, flush events, free
@@ -5576,5 +5748,5 @@ const registerZeroGpuOffscreenMessaging = (options = {}) => {
5576
5748
  return state;
5577
5749
  };
5578
5750
 
5579
- export { ZEROGPU_OFFSCREEN_MESSAGES, initZeroGpuOffscreen, registerZeroGpuOffscreenMessaging };
5751
+ export { ZEROGPU_OFFSCREEN_MESSAGES, initZeroGpuOffscreen, registerZeroGpuOffscreenMessaging, setCustomParams };
5580
5752
  //# sourceMappingURL=zerogpu-offscreen.js.map