@afterpack/wasm 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import type { AfterpackConfig, FileInput, Result } from "./contract.js";
1
+ import type { AfterpackConfig, CallerContext, FileInput, Result } from "./contract.js";
2
2
  export * from "./contract.js";
3
3
  /**
4
4
  * Obfuscate several files in one build. Results come back in input order. With `config.key` set,
5
- * the build runs in AfterPack's cloud. Throws an {@link ObfuscationError} when the build cannot ship.
5
+ * the build runs in AfterPack's cloud, and a tool wrapping this call names itself in `context`.
6
+ * Throws an {@link ObfuscationError} when the build cannot ship.
6
7
  */
7
- export declare function obfuscateAll(files: FileInput[], config?: AfterpackConfig): Promise<Result[]>;
8
+ export declare function obfuscateAll(files: FileInput[], config?: AfterpackConfig, context?: CallerContext): Promise<Result[]>;
8
9
  /** Obfuscate one file. Throws an {@link ObfuscationError} when the build cannot ship. */
9
- export declare function obfuscate(input: string | Uint8Array | FileInput, config?: AfterpackConfig): Promise<Result>;
10
+ export declare function obfuscate(input: string | Uint8Array | FileInput, config?: AfterpackConfig, context?: CallerContext): Promise<Result>;
10
11
  /** The AfterPack engine version, e.g. `0.1.0`. */
11
12
  export declare function version(): Promise<string>;
package/dist/api.js CHANGED
@@ -66,11 +66,50 @@ const REQUEST_TIMEOUT_MS = 330_000;
66
66
  function sleep(ms) {
67
67
  return new Promise((resolve) => setTimeout(resolve, ms));
68
68
  }
69
+ function configKey(config) {
70
+ const key = config.key;
71
+ if (key === undefined || key === null)
72
+ return null;
73
+ if (typeof key === "string" && key.trim() !== "")
74
+ return key.trim();
75
+ throw new ObfuscationError("AfterPack refused this build: invalid configuration at `key` -- expected a non-empty " +
76
+ "string, your AfterPack Pro key. No output was emitted. Remove `key` to build locally on Free.", []);
77
+ }
69
78
  function engineConfigWithoutKey(config) {
70
79
  const { key: _key, ...rest } = config;
71
80
  return rest;
72
81
  }
73
- function buildCloudForm(files, paths, sources, kinds, engineConfig) {
82
+ const MAX_CLIENT_LEN = 128;
83
+ const MAX_GIT_REF_LEN = 200;
84
+ function wireText(value, maxLength, allowed) {
85
+ if (typeof value !== "string")
86
+ return undefined;
87
+ const text = value.trim();
88
+ return text.length <= maxLength && allowed.test(text) ? text : undefined;
89
+ }
90
+ function cloudContext(context) {
91
+ const client = context?.client === undefined
92
+ ? `@afterpack/wasm/${PACKAGE_VERSION}`
93
+ : wireText(context.client, MAX_CLIENT_LEN, /^[A-Za-z0-9@/._+-]+$/);
94
+ const headers = {
95
+ "X-AfterPack-Client-Version": PACKAGE_VERSION,
96
+ "X-AfterPack-Client-Timeout-Ms": String(REQUEST_TIMEOUT_MS),
97
+ };
98
+ if (client !== undefined)
99
+ headers["X-AfterPack-Client"] = client;
100
+ const commitSha = wireText(context?.commitSha?.toLowerCase(), 40, /^[0-9a-f]{7,}$/);
101
+ const ref = wireText(context?.ref, MAX_GIT_REF_LEN, /^[A-Za-z0-9._/+-]+$/);
102
+ if (commitSha === undefined && ref === undefined)
103
+ return { headers };
104
+ return {
105
+ headers,
106
+ git: {
107
+ ...(commitSha === undefined ? {} : { commitSha }),
108
+ ...(ref === undefined ? {} : { ref }),
109
+ },
110
+ };
111
+ }
112
+ function buildCloudForm(files, paths, sources, kinds, engineConfig, git) {
74
113
  const manifestFiles = files.map((file, i) => {
75
114
  const entry = { filePath: paths[i], partName: `file-${i}` };
76
115
  if (file.sourceMap !== undefined)
@@ -81,7 +120,12 @@ function buildCloudForm(files, paths, sources, kinds, engineConfig) {
81
120
  return entry;
82
121
  });
83
122
  const form = new FormData();
84
- form.append("batch", JSON.stringify({ version: "1", files: manifestFiles, config: engineConfig }));
123
+ form.append("batch", JSON.stringify({
124
+ version: "1",
125
+ files: manifestFiles,
126
+ config: engineConfig,
127
+ ...(git === undefined ? {} : { git }),
128
+ }));
85
129
  files.forEach((file, i) => {
86
130
  form.append(`file-${i}`, new Blob([sources[i]], { type: "application/javascript" }), paths[i]);
87
131
  if (file.sourceMap !== undefined) {
@@ -206,7 +250,7 @@ function clampRetryAfter(header) {
206
250
  const seconds = Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_RETRY_AFTER_SECONDS;
207
251
  return Math.min(seconds, MAX_RETRY_AFTER_SECONDS);
208
252
  }
209
- async function requestCloudBatch(key, form) {
253
+ async function requestCloudBatch(key, form, identity) {
210
254
  const url = `${cloudApiBase()}/v1/obfuscate/batch`;
211
255
  let rateLimitedOnce = false;
212
256
  let backoffAttempt = 0;
@@ -215,12 +259,7 @@ async function requestCloudBatch(key, form) {
215
259
  try {
216
260
  response = await fetch(url, {
217
261
  method: "POST",
218
- headers: {
219
- Authorization: `Bearer ${key}`,
220
- "X-AfterPack-Client-Version": PACKAGE_VERSION,
221
- "X-AfterPack-Client": `@afterpack/wasm/${PACKAGE_VERSION}`,
222
- "X-AfterPack-Client-Timeout-Ms": String(REQUEST_TIMEOUT_MS),
223
- },
262
+ headers: { Authorization: `Bearer ${key}`, ...identity },
224
263
  body: form,
225
264
  signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
226
265
  });
@@ -327,9 +366,10 @@ function inRequestOrder(paths, results) {
327
366
  return results[at];
328
367
  });
329
368
  }
330
- async function obfuscateAllCloud(files, paths, sources, kinds, key, config) {
331
- const form = buildCloudForm(files, paths, sources, kinds, engineConfigWithoutKey(config));
332
- const response = await requestCloudBatch(key, form);
369
+ async function obfuscateAllCloud(files, paths, sources, kinds, key, config, context) {
370
+ const { headers, git } = cloudContext(context);
371
+ const form = buildCloudForm(files, paths, sources, kinds, engineConfigWithoutKey(config), git);
372
+ const response = await requestCloudBatch(key, form, headers);
333
373
  const boundary = extractBoundary(response.headers.get("content-type"));
334
374
  if (boundary === null) {
335
375
  throw new ObfuscationError("AfterPack Pro cloud returned a 200 response with no multipart boundary", []);
@@ -347,13 +387,14 @@ async function obfuscateAllCloud(files, paths, sources, kinds, key, config) {
347
387
  }
348
388
  return ordered.map((result, i) => new ObfuscatedFile(files[i].path ?? null, result.output, result.outputMap ?? null, [], null));
349
389
  }
350
- export async function obfuscateAll(files, config) {
390
+ export async function obfuscateAll(files, config, context) {
351
391
  const paths = files.map((file, i) => enginePath(file, i, files.length));
352
392
  const sources = files.map((file) => sourceToString(file.source));
353
393
  const kinds = fileSourceTypes(files);
354
394
  const build = config?.seed === undefined ? { ...config, seed: randomSeed() } : config;
355
- if (build.key !== undefined) {
356
- return obfuscateAllCloud(files, paths, sources, kinds, build.key, build);
395
+ const key = configKey(build);
396
+ if (key !== null) {
397
+ return obfuscateAllCloud(files, paths, sources, kinds, key, build, context);
357
398
  }
358
399
  let results;
359
400
  try {
@@ -381,9 +422,9 @@ export async function obfuscateAll(files, config) {
381
422
  }
382
423
  return results.map((result, i) => new ObfuscatedFile(files[i].path ?? null, result.code, result.sourceMap, result.diagnostics, result.protectionMap ?? null));
383
424
  }
384
- export async function obfuscate(input, config) {
425
+ export async function obfuscate(input, config, context) {
385
426
  const file = isFileInput(input) ? input : { source: input };
386
- const [only] = await obfuscateAll([file], config);
427
+ const [only] = await obfuscateAll([file], config, context);
387
428
  return only;
388
429
  }
389
430
  export async function version() {
@@ -51,7 +51,7 @@ export interface RegionConfig {
51
51
  export interface AfterpackConfig {
52
52
  /** The random seed. Unset, every build produces different output; set it to reproduce a build. */
53
53
  seed?: number | string;
54
- /** Your AfterPack Pro key. With a key, the build runs in AfterPack's cloud with much stronger protection. */
54
+ /** Your AfterPack Pro key. Set, the build runs in AfterPack's cloud. https://www.afterpack.dev/docs/pro */
55
55
  key?: string;
56
56
  /** A named protection level. Defaults to `light`. */
57
57
  preset?: Preset;
@@ -247,4 +247,16 @@ export declare class ObfuscationError extends Error {
247
247
  notices: Notice[] | null;
248
248
  });
249
249
  }
250
+ /**
251
+ * Who is calling and where a cloud build came from. Shown on cloud builds in your dashboard; never
252
+ * changes the output. A malformed value is dropped.
253
+ */
254
+ export interface CallerContext {
255
+ /** The commit the build ran on, 7 to 40 hex characters. */
256
+ commitSha?: string;
257
+ /** The branch or tag the build ran on. */
258
+ ref?: string;
259
+ /** The tool calling AfterPack, as `<name>/<version>`. Defaults to this package's own. */
260
+ client?: string;
261
+ }
250
262
  export {};
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "0.2.7-rc.202610170324";
1
+ export declare const PACKAGE_VERSION = "0.2.8-rc.202610182306";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = "0.2.7-rc.202610170324";
1
+ export const PACKAGE_VERSION = "0.2.8-rc.202610182306";
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@afterpack/wasm",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "description": "The AfterPack JavaScript obfuscator as WebAssembly, for Cloudflare Workers and Node",
5
5
  "type": "module",
6
6
  "main": "./dist/node.js",
package/readme.md CHANGED
@@ -52,6 +52,8 @@ await version(); // "0.2.1"
52
52
 
53
53
  `obfuscate` accepts a string, a `Uint8Array`, or a file object `{ path, source, sourceMap, sourceType }`, where `sourceMap` is the file's existing map to chain and `sourceType` (`"auto"`, `"module"` or `"script"`) overrides the build's for that file. Each result has `code`, `bytes`, `sourceMap` and `diagnostics`. The second argument is the config. See the [configuration reference](https://www.afterpack.dev/docs/config) and the [presets](https://www.afterpack.dev/docs/presets).
54
54
 
55
+ A tool that wraps AfterPack can name itself to the cloud in an optional third argument, `obfuscate(source, config, { client: "my-tool/1.0.0" })`. It never changes the output.
56
+
55
57
  ## Errors
56
58
 
57
59
  If a build can't ship safely, the call throws an `ObfuscationError` with the engine's diagnostics. That covers an invalid config, a blocking diagnostic, or output that would go out unprotected.
@@ -75,8 +77,8 @@ Without a key, all of Free runs inside your Worker or Node process, with every p
75
77
 
76
78
  | Measure | Bytes | |
77
79
  |---|---:|---|
78
- | Raw `.wasm` | 4,569,276 | 4.36 MiB |
79
- | Gzipped | 1,306,517 | 1.25 MiB |
80
+ | Raw `.wasm` | 4,573,321 | 4.36 MiB |
81
+ | Gzipped | 1,307,772 | 1.25 MiB |
80
82
 
81
83
  This fits Cloudflare's Worker size limit on both the free and paid plans. CPU time is the tighter limit: the free plan allows 10 ms per request, and obfuscating a 185 KB bundle at `complexity: 8` takes about 263 ms on an Apple M-series laptop. Plan on Workers Paid for real bundles.
82
84